AngularJS ng-repeat:视图不会更新模型更改...

时间:2013-12-25 04:22:32

标签: javascript angularjs

我正在尝试通过ng-submit向我的视图中添加项目。函数getTemp按预期工作,并且$ scope.temperatures已正确更新(我可以在控制台中看到它),但新数据值不会出现在视图中。我不确定什么没有被妥善束缚。

我在这里查看了其他相关问题,但似乎没有完全相同。

查看:

<div ng-controller="tempCtrl" class="container">
        <form id="zipCodeForm"  ng-submit="submit()" ng-controller="tempCtrl">
            <input id="zipCodeInput" ng-model="text" name="text" type="text"> </input>
            <input id="zipSubmit" type="submit" value="Submit" class="btn btn-large btn-primary"></input>
        </form>

        <div>
            <h4 ng-repeat='item in temperatures'>
                Zip code is {{item.zip}} and temperature is {{item.temp}}
            </h4>
        </div>
    </div>  

MODEL:

var temperatureApp = angular.module('temperatureApp', []);

temperatureApp.controller('tempCtrl', function ($scope, $http) {
$scope.temperatures = [
                    {zip: "10003", temp: "43"},
                    {zip: "55364", temp: "19"}
];  

function getTemp(zipCode){
    $http({method: 'GET', url: 'http://weather.appfigures.com/weather/' + zipCode}).
    success(function(data){
        tempObject = data;
        $scope.temperatures.push({zip: "10003", temp: tempObject.temperature.toString()});
    });
}

$scope.submit = function() {
    getTemp(this.text);
    console.log($scope.temperatures);
}

})

1 个答案:

答案 0 :(得分:6)

问题是您的表单中有ng-controller="tempCtrl"。这将 创建当前范围的子范围 。因此,放入此范围的任何对象都不会影响当前范围。尝试删除它:

 <div ng-controller="tempCtrl" class="container">
     <form id="zipCodeForm" ng-submit="submit()"> //remove your redundant ng-controller
         <input id="zipCodeInput" ng-model="text" name="text" type="text"> </input>
         <input id="zipSubmit" type="submit" value="Submit" class="btn btn-large btn-primary"></input>                  
     </form>
     <div>
          <h4 ng-repeat='item in temperatures'>
              Zip code is {{item.zip}} and temperature is {{item.temp}}
          </h4>
     </div>
</div>

DEMO