[英]$emit is called more than once angularJS
好的,這段代碼多次調用了我的$ emit函數。 我希望它只調用一次。
我有一個控制器和兩個指令。 綜上所述,我想讓一個指令向控制器發送消息,而控制器向另一指令發送消息。 需要幫忙。
來自newby angularJS編碼器。
enter code here
app.controller("myCtrl", ['$scope', '$http', '$routeParams', 'myCounter', '$rootScope', function ($scope, $http, $routeParams, myCounter, $rootScope) {
///////////////////////////////////////////
Listener = $scope.$on('eventEmit', function (event, args) {
event.stopPropagation();
console.log("hi from controller");
// broadcast down to directives
childPosition = 0;
$scope.$broadcast('eventBroadcast', childPosition);
});
// destroy listener
$scope.$on('$destroy', Listener);
}]);
“頁面”指令一次只能顯示1個“頁面”。 一個頁面不能存在於另一個頁面的內部,哪個頁面可見是由對控制器的命令確定的
enter code here
app.directive('myPage', function (myCounter) {
return {
template: '<div ng-show = "showContent" >content {{counter}}</div>',
restrict: 'EA',
controller: 'myCtrl',
scope: {
nextPage: '&',
showContent:'<'
},
link: function (scope, element, attr) {
///////////////////////////////////////////
scope.$on('eventBroadcast', function (event, args) {
console.log("hi from directive");
});
}
};
})
“事件”指令將偵聽其父元素上的事件,並通過偵聽事件發生的時間發送命令。 2個屬性類型–應偵聽什么事件(如“單擊”)操作–事件發生時應發生什么? 例如,事件指令應發送一條消息,告知控制器調用NextPage函數
enter code here
app.directive('myEvent',['$rootScope', function (myCounter,$rootScope ) {
return {
restrict: 'EA',
controller: 'myCtrl',
template: '<input type = "button" ng-click = "handlePrev()" ng-
transclude>Prev</input>' +
'<input type = "button" ng-click = "handleNext()" ng-
transclude>Next</input>',
transclude:true,
link: function ($scope, element, attrs) {
$scope.handleNext = function () {
$scope.functionValue = "nextPage";
pageController($scope.functionValue, $scope);
console.log("Clicked next", $scope.functionValue);
}
$scope.handlePrev = function () {
$scope.functionValue = "prevPage";
pageController($scope.functionValue, $scope);
}
}
};
}])
pageController = function ( string, $scope) {
myEmitter = $scope.$emit('eventEmit', string);
$scope.$emit('$destroy', myEmitter);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.