让子控制器监听父控制器的变化[重复]
Posted
技术标签:
【中文标题】让子控制器监听父控制器的变化[重复]【英文标题】:have children controllers listen for change of a parent controller [duplicate] 【发布时间】:2015-02-14 06:17:10 【问题描述】:我需要一个父包装器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
。我可以在子控制器中有一些东西在wrapperCtrl
运行中监听$scope.changeSafe
函数并重新绑定它是$scope.safe
【问题讨论】:
【参考方案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
);
【讨论】:
以上是关于让子控制器监听父控制器的变化[重复]的主要内容,如果未能解决你的问题,请参考以下文章