当控制器中的模型在Angular Js中执行时,模板不会更改

时间:2015-12-12 16:24:52

标签: javascript angularjs

我有一个控制器,它使用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()当我使用它的指令时隐式,但在我的情况下它并不反映我的模型中的变化到我的模板。

感谢您的帮助

2 个答案:

答案 0 :(得分:0)

答案 1 :(得分:0)

代码中的问题是您定义了ng-controller两次 - 一次在父div容器上,另一次在select元素上。

使用ng-controller为状态下拉列表创建一个新的控制器实例,该实例与父div元素的控制器实例不同。

如果您在状态下更改了某个值,则下拉控制将转到您选择元素上的第二个statesController实例,并在那里更新范围内的城市。但是,HTML模板中的cities元素实际上是从div容器绑定到控制器。

只需删除状态下拉列表中的ng-controller即可。

此处有pen并发生了此更改:)