javascript AngularJS ng-repeat:视图不会在模型更改时更新......
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20769021/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
AngularJS ng-repeat: view doesn't update on model change…
提问by Thomas Murphy
I am attempting to add items to my view via ng-submit. The function getTemp works as expected, and $scope.temperatures is properly updated (I can see it in the console), however the new data values do not appear in the view. I am unsure what is not being properly bound.
我正在尝试通过 ng-submit 将项目添加到我的视图中。函数 getTemp 按预期工作,并且 $scope.temperatures 已正确更新(我可以在控制台中看到它),但是新的数据值没有出现在视图中。我不确定什么没有被正确绑定。
I've looked through the other related questions here, but none seem to be quite the same.
我在这里查看了其他相关问题,但似乎没有一个完全相同。
VIEW:
看法:
<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);
}
})
回答by Khanh TO
The problem is you have ng-controller="tempCtrl"
in your form. This will create its own child scopeof the current scope. Therefore any object you put into this scope will not affect the current scope. Try removing it:
问题是你有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>