【发布时间】:2013-08-21 12:12:58
【问题描述】:
我在从父范围到子范围的广播事件中遇到问题,我认为根核心可能是子控制器未初始化。
假设我有html:
<div ng-controller="ParentController">
<button type="button" ng-click="show()">Show Template</button>
<div ng-if="showTemplate">
<div ng-include="'template.html'" ng-controller="ChildController"></div>
</div>
</div>
和控制器:
var myApp = angular.module("myApp", []);
myApp.controller('ParentController', ['$scope', function ($scope) {
$scope.show = function(){
$scope.showTemplate = true;
$scope.$broadcast("showEvent", 1);
};
}]);
myApp.controller('ChildController', ['$scope', function ($scope) {
$scope.$on("showEvent", function(event, id){
alert(id);
});
}]);
当按钮Show Template被点击时,标志showTemplate被设置为显示模板,同时一个事件showEvent被广播到子作用域。
但ChildController 中的作用域无法捕获此事件,因为子控制器可能稍后会初始化。
有什么办法可以解决这个问题吗?
【问题讨论】:
标签: javascript angularjs