angularJS $范围更改不更新视图

时间:2016-03-13 23:27:39

标签: javascript angularjs

我一直在反对angularJS $范围问题。我有一个数组,我在控制器功能中更新。根据我的控制台日志,其中的值确实已更改。但是,视图未更新。这是片段。

//array initialisation

    $scope.fieldSuggestions = []

//modifying function

  $scope.changeCurrentInput = function(fieldName, eye) {
    for(var field in $scope.test){
      console.log($scope.test[field].name)
      if($scope.test[field].name === fieldName){
        console.log($scope.test[field].values)
        console.log("be4 update")
        console.log($scope.fieldSuggestions)
        $scope.fieldSuggestions = $scope.test[field].values;
        console.log("after update")
        console.log($scope.fieldSuggestions)
      }
    }
  };

//view

 <div ng-repeat="choice in fieldSuggestions">       
    <button class="button button-positive">{{choice}}</button>
</div>

更详细信息......

我认为这可能是相关的。我有一个父视图和几个子视图。这些路由中的每一个使用相同的控制器。即:routes.js中的属性控制器对所有人来说都是一样的。调用修改函数的按钮位于子视图中,但未更新的ng-repeat位于父视图中。

3 个答案:

答案 0 :(得分:1)

由于您正在更改嵌套属性,因此Angular不会触发摘要。您只需添加linkcontroller函数

即可解决此问题
$scope.$watchCollection('fieldSuggestions', function(newFieldSuggestions, oldFieldSuggestions) {
  $scope.fieldSuggestions= newFieldSuggestions;
}); 

值得指出的是:对于大型集合和复杂对象而言,这可能不是最佳选择。

答案 1 :(得分:1)

结果我通过声明我的子控制器与父控制器是同一个来遮蔽父fieldSuggestions变量。解决方案是不要在子路由上重新声明控制器,因为它会自动查看父路由。

感谢所有帮助过的人。

答案 2 :(得分:0)

我认为由于嵌套更改,它无法在那时更新值。您可以使用$ scope。$ apply()来获取最新的更新值 比如.... $ scope。$ apply($ scope.fieldSuggestions = $ scope.test [field] .values);