在 app.js 中,我在 $rootScope 上广播的回调函数中使用,以在第二个 Controller 上触发方法。
function onSuccess(state) {
if (state != true) {
} else {
$rootScope.$broadcast('proximityCatched', null);
}
//console.log('Proximity state: ' + (state ? 'near' : 'far'));
};
在 Controller 上我有监听器:
$rootScope.$on('proximityCatched', function () {
alert("TEST");
});
问题是alert("TEST");被触发两次。
我尝试使用 stopPropagation 或在正常范围内使用广播来找到任何可行的解决方案,但没有运气。
请问我该如何以正确的方式做到这一点?
感谢您的建议。
编辑:路由器配置:
.config(function($stateProvider, $urlRouterProvider) {
$stateProvider
.state('game', {
url: "/game",
templateUrl: "templates/game.html",
controller: "GameCtrl"
})
.state('home', {
url: "/home",
templateUrl: "templates/home.html",
controller: "HomeCtrl"
})
// if none of the above states are matched, use this as the fallback
$urlRouterProvider.otherwise('/home');
});
最佳答案
如果您连接 Controller 两次,它将调用两次。
检查您是否在routes
配置和html中附加 Controller (通过使用ng-controller
),如果您附加两次(使用两种方式),请删除一个。
关于javascript - AngularJS : How to avoid - Broadcast event called from app. js 被触发两次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30975727/