简体   繁体   中英

In an Angular directive, how do you reapply an event listener after the event has been removed?

This might be a result of me lacking knowledge in Angular and if so, forgive me in advance if that is the case.

In Angular, suppose I have a directive which is bound to an element as an attribute.

<div my-directive></div>

In the directive, I have a click event which will remove the click event itself.

app.directive("myDirective", function() {
   return {
      link: function(scope, ele, attr, ctrl) {
          ele.on("click", function() {
              ele.off("click");
              console.log("Click event removed");
          });
      }
   }
});

I want to set the click event on to the same div from this directive again (let's say after a button is clicked). How do I accomplish this?

You can use like this-

app.directive("myDirective", function() {
   return {
      link: function(scope, ele, attr, ctrl) {
          ele.on("click", function() {
              ele.unbind("click");
              console.log("Click event removed");

             angular.element(ele).bind("click");
          });

      }
   }
});
app.directive("myDirective", function() {
   return {
      link: function(scope, ele, attr, ctrl) {
          ele.on("click", function() {
              angular.element(ele).off('click');
              console.log("Click event removed");
          });
      }
   }

});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM