javascript - 在用angularjs做一个单页面应用,父类怎么通过$broadcast把变量传给子类的子类,求大神指教
PHPz
PHPz 2017-04-10 17:51:49
0
1
290

类似于这样的情况
<p ng-controller="parentCtr">

<p ng-controller="childCtr1">
    <p ng-controller="childCtr2">
    </p>
</p>

</p>
这些控制器都是在一个module里,我需要的是把parentCtr里的变量传给childCtr2
然后在childCtr2中通过$on获取

PHPz
PHPz

学习是最好的投资!

reply all(1)
迷茫

HTML

<p ng-controller="ParentCtrl">
    <button ng-click="click()">change</button>
    <p ng-controller="ChildCtrl1">
        <p ng-controller="ChildCtrl2">

        </p>
    </p>
</p>

SCRIPT

angular.module('myApp', [])
        .controller('ParentCtrl', function ($scope) {
            $scope.click = function () {
                $scope.$broadcast('change', {name: 'xxx'});
            }
        })
        .controller('ChildCtrl1', function ($scope) {

        })
        .controller('ChildCtrl2', function ($scope) {
            $scope.$on('change', function (event, obj) {
                console.log(obj);
            });
        });

SCOPE

Scope是继承的,如果只是单纯想获取父Scope的数据,这样就可以了

angular.module('myApp', [])
        .controller('ParentCtrl', function ($scope) {
            $scope.data=[1,2,3];               
        })
        .controller('ChildCtrl1', function ($scope) {

        })
        .controller('ChildCtrl2', function ($scope) {
            console.log($scope.data);                
        });
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template