我有一个控制器,它使用http服务加载我的作用域对象中的数据。 这最初是有效的,但当我通过用户事件更改我的模型时,它不会反映在模板中
这是我的控制器
myApp.controller('statesController',['$scope','$http',function ($scope,$http){
$http.get('data/states.json').success(function(data){
$scope.states=data;
});
$scope.loadCities=function(state){
$http.get('someURLforExternalWebService?path=/Cities?state='+state).success(function(data){
var jsonData = $.xml2json(data); //the data I get back is in XML
console.log('cities', jsonData);
$scope.cities=jsonData.row;
console.log('scope ',$scope);
});
$scope.states="lets change states";
}
}]);
这是我的HTML(我已经包含整个HTML文件以防万一)
<html ng-app="myApp">
<head>
//header includes
</head>
<body>
<div id='test'>
<select class="form-control" ng-controller="typeController" >
<option ng-repeat="types in row" >{{types.type}}</option>
</select>
<div ng-controller="statesController" >
<select class="form-control" ng-model="state" ng-options="state.abbreviation for state in states" ng-change="loadCities(state.abbreviation)" ng-controller="statesController" >
</select>
{{states}} //this is were I trying to test if it changes
<select class="form-control" ng-model="city" ng-options="city.city for city in cities" >
</select>
</div>
</div>
</body>
</html>
如果您注意到{{states}}即使在模型更改后,即在触发ng-change事件后仍然保持不变。我通过登出范围
来确认这一点我尝试使用$ scope。$ apply()显式
但它给我一个错误,说消化已在进行中,
我理解角度调用。$ apply()当我使用它的指令时隐式,但在我的情况下它并不反映我的模型中的变化到我的模板。
感谢您的帮助
答案 0 :(得分:0)
不要在ng-model指令中使用原语。
https://github.com/angular/angular.js/wiki/Understanding-Scopes
https://www.youtube.com/watch?v=ZhfUv0spHCY&feature=youtu.be&t=30m
答案 1 :(得分:0)
代码中的问题是您定义了ng-controller
两次 - 一次在父div
容器上,另一次在select
元素上。
使用ng-controller
为状态下拉列表创建一个新的控制器实例,该实例与父div
元素的控制器实例不同。
如果您在状态下更改了某个值,则下拉控制将转到您选择元素上的第二个statesController
实例,并在那里更新范围内的城市。但是,HTML模板中的cities
元素实际上是从div
容器绑定到控制器。
只需删除状态下拉列表中的ng-controller
即可。
此处有pen并发生了此更改:)