我开始在需要重构的项目上使用Angular,但我不能从头开始,所以现在我需要插入一些需要动态编译的带有Angular属性的html,比如这样:
var html = "<div ng-controller='MyController'><p ng-click="raiseEvent()">Click Me</p></div>";
var $injector = angular.injector(['ng', 'MyProject']);
$injector.invoke(function($rootScope, $compile) {
$('body').append($compile(html)($rootScope));
});
我有两个控制器,如下所示:
function MyController($scope, $rootScope) {
$scope.raiseEvent = function(){
$rootScope.$broadcast('handleBroadcast');
}
};
function MyOtherController($scope) {
$scope.$on('handleBroadcast', function (event, data) {
// Code goes here
});
};
我的目的是点击“Clik Me”为MyOtherController播放消息。当我按下“Click Me”时调用raiseEvent,但MyOtherController中的监听器没有捕获该事件。 Fuhermore,如果我在HTML文件上使用HTML,我不会得到这个错误,这让我相信问题在于$ compile方法。有什么建议?
答案 0 :(得分:0)
您没有在视图上使用MyOtherController
。
var myApp = angular.module('myApp',[]);
function MyController($scope, $rootScope) {
$scope.raiseEvent = function(){
$rootScope.$broadcast('handleBroadcast');
}
}
function MyOtherController($scope) {
$scope.$on('handleBroadcast', function (event, data) {
alert("I've called!");
});
}
在你看来:
<div ng-controller="MyController">
<p ng-click="raiseEvent()">Click Me</p>
</div>
<div ng-controller="MyOtherController">
</div>
这应该有用。
我为你创建了JSFiddle。
另外,我建议你在这里调查角度事件:http://toddmotto.com/all-about-angulars-emit-broadcast-on-publish-subscribing/