繁体   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