Search code examples
angularjsparent-childcontrollers

sharing data of parent controllers between two child controllers


I am trying to share data between two controllers (child1 and child2) which are children of one common controller (parent). index.html is :

<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>

I have defined three controllers as (parent, child1 and 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;
}]);

But the page is not showing anything. What is wrong with this code?


Solution

  • Use angular's $timeout service instead of 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(); 
    }]);