簡體   English   中英

$ emit不止一次被調用angularJS

[英]$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);
}

解決此問題的方法有三種:

  1. 確保僅一次調用一次發射(可能無法執行)。

  2. 查看觸發的2個事件。 他們是同一事件嗎? 例如,它們都是單擊事件還是一個單擊事件而一個是不同事件。 如果您只對click事件感興趣,請執行..

     if (event.target.type === 'click') { // run your code here } 
  3. 如果所有其他操作均失敗,則可以對事件進行反跳或限制,這將意味着它無法在給定的時間范圍內被兩次調用。 例如,它將確保不能在300ms內兩次調用它。 第二個呼叫將被忽略。 如果要使用此方法,請使用Lodash 防反跳或Lodash 節流閥

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM