从子级更新父级范围不会更新ngrepeat

时间:2015-09-02 10:56:16

标签: javascript angularjs angularjs-scope angularjs-ng-repeat

我在与父控制器通信子控制器时出现问题, 我有一个函数将数据推送到ngrepeat中包含的父数组。

在推送父数组后正确添加,其长度在父控制器中正确显示,但ngrepeat不刷新。

<div ng-controller="parentCtrl">
This works {{shared.arr.length}} <br/>
This works Too{{shared.arr|json}} <br/>

<div ng-repeat="a in shared.arr">
{{a}} This dont, it only show old data.
</div>

<section ng-contoller="childCtrl">
<button ng-click="test()">Test</button>
</section>
</div>
angular.module('testApp')
  .controller('parentCtrl', function ($scope) {
$scope.shared = {arr:[1,2]};
});
  .controller('childCtrl', function ($scope) {
$scope.test = function(){$scope.shared.arr.push(4);}
});

2 个答案:

答案 0 :(得分:1)

angular.module('testApp', [])
  .controller('parentCtrl', ['$scope', parentCtrl])
  .controller('childCtrl', ['$scope', childCtrl]);

function parentCtrl ($scope) {
  $scope.shared = {
    arr: [1, 2]
  };
}
function childCtrl ($scope) {
  $scope.test = function (arr) {
    arr.push(4);
  }
}

<div ng-controller="childCtrl">
    <button ng-click="test(shared.arr)">Test</button>
</div>

http://jsfiddle.net/kikill/zhzb3pxh/

试试这段代码。

有2个错误: 1)ng-controller =“childCtrl”,而不是ng-contoller =“childCtrl” 2)你传入'test'函数parent的变量。它可以产生许多错误,在这个例子中不是那么清楚,但它可以。 使用'controller as'语法。你可以阅读这个here

答案 1 :(得分:0)

由于这个代码在我的情况下运行正常,我会假设在你的代码中你也犯了在<ng-contoller="childCtrl">中编写控制器作为控制器的错误,这是一个非常愚蠢的错误:)

相关问题