首页 > 在用angularjs做一个单页面应用,父类怎么通过$broadcast把变量传给子类的子类,求大神指教

在用angularjs做一个单页面应用,父类怎么通过$broadcast把变量传给子类的子类,求大神指教

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

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

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


HTML

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

        </div>
    </div>
</div>

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);                
        });
【热门文章】
【热门文章】