让子控制器监听父控制器的更改

时间:2014-12-16 01:30:06

标签: javascript angularjs angularjs-scope

我需要父包装器controller来始终运行并将数据推送到任何子容器。当父包装器上的事件更改属性的范围时,我需要孩子controllers更新

secure.controller('wrapperCtrl', function ($scope, storeFactory, safeFactory) {
    //get first store
    storeFactory.setStoreSummary(1).then(function (storeData) {
        $scope.store = storeData

        safeFactory.setSafe(storeData.safes[0].id).then(function(safeData){
            $scope.safe = safeData;
        });
    });

    $scope.changeSafe = function (safeId) {
        safeFactory.setSafe(safeId).then(function (safeData) {
            $scope.safe = safeData;
        });
    }
});

index.html页面上,我有以下内容:

<div class="pageTitle">
    <h1>{{title}}</h1>
    <h2>{{store.storeName}}</h2>
    <ul class="safes">
        <li ng-repeat="safe in store.safes"><a href="#_" ng-class="isActive(safe.id)" ng-click="changeSafe(safe.id)" ng-cloak>{{safe.name}}</a></li>
    </ul>
</div>
<div ng-view class="fade"></div>

您可以看到ng-view加载子controllers。我是否可以在子控制器中查看$scope.changeSafe运行中的wrapperCtrl函数并重新绑定它$scope.safe

1 个答案:

答案 0 :(得分:1)

如果您需要更明确的答案:

secure.controller('wrapperCtrl', function ($scope, storeFactory, safeFactory) {
    //get first store
    ...

    $scope.changeSafe = function (safeId) {
        safeFactory.setSafe(safeId).then(function (safeData) {
            $scope.safe = safeData;
            $scope.$broadcast('changeSafely'); // broadcast changeSafely event in parent ctrl
        });
    }
});

secure.controller('childCtrl', function($scope, ...) {

    function doSomething(){
        ...
    }

    $scope.$on('changeSafely', doSomething); // capture event and do you stuff

});