共享两个子控制器之间的父控制器的数据

时间:2013-09-23 08:07:11

标签: angularjs parent-child controllers

我正在尝试在两个控制器(child1和child2)之间共享数据,这两个控制器是一个公共控制器(父级)的子级。 index.html是:

<div ng-controller="parent">
    <ul>
    <p>Parent controller</p>
        <li ng-repeat="item in items">
            {{item.id}}
        </li>
    </ul>
    <div ng-controller="child1">
        <ul>
            <p>First DIV :</p>
            <li ng-repeat="item in items">
                {{item.id}}
            </li>
        </ul>
    </div>
    <div ng-controller="child2">
        <ul>
            <p>Second DIV :</p>
            <li ng-repeat="item in items">
                {{item.id}}
            </li>
        </ul>
    </div>
</div>

我已将三个控制器定义为(parent,child1和child2):

   var myApp = angular.module('myApp', []);

myApp.controller('parent',['$scope', function($scope) {
    $scope.items = [
        {'id':1},
        {'id':2},
        {'id':3},
        {'id':4}
    ];

    $scope.items.push({'id':10});

    $scope.myfun = function() {
        setTimeout(function(){
            $scope.items.push({'id':20});
            alert("inserting 20....!");
        },3000);
    }

    $scope.myfun(); 
}]);

myApp.controller('child1', ['$scope', function($scope) {
    $scope.items = $scope.$parent.items;

}]);

myApp.controller('child2', ['$scope', function($scope) {
    $scope.items = $scope.$parent.items;
}]);

但页面没有显示任何内容。这段代码有什么问题?

1 个答案:

答案 0 :(得分:2)

使用angular的$timeout服务而不是setTimeout:

myApp.controller('parent',['$scope','$timeout', function($scope, $timeout) {
    $scope.items = [
        {'id':1},
        {'id':2},
        {'id':3},
        {'id':4}
    ];

    $scope.items.push({'id':10});

    $scope.myfun = function() {
       $timeout(function(){
            $scope.items.push({'id':20});
            alert("inserting 20....!");
        },3000);
    }

    $scope.myfun(); 
}]);