Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS : Listen for click events on a button outside of a directive

I am new to angularjs. I am building an angularjs SPA. The application page has two sections - a buttons area and a application area. The application area is where my views are loaded. The buttons area is the same for each view, hence I do not include it in the views template but rather keep it in the application window. My problem is that I would like the various directives that I load into the application area to respond to clicks in the buttons area. How do I listen to click (or any other event) that originate outside of a directive? Thanks much in advance!

like image 884
rmg.n3t Avatar asked May 24 '14 16:05

rmg.n3t


1 Answers

You just need to reference the button and attach an event handler to it.

Example:

app.directive('directiveName', function () {

  return {
    link: function (scope, element, attrs) {

      // Get a reference to the button DOM element
      var buttonDOMElement = document.querySelector('#button1');

      // Wrap it as a jqLite element
      var button = angular.element(domElement);

      var onButtonClick = function () {
        // Do something
      };

      button.on('click', onButtonClick);

      scope.$on('$destroy', function () {
        button.off('click', onButtonClick);
      });
    }
  };
});

Demo: http://plnkr.co/edit/4XvPT8r9USWHnbdu1ZHX?p=preview

Note that event handlers attached like this lives "outside of Angular". This means that if your handler updates for example a scope value that is bound to the view, you need to explicitly tell Angular, or the change will not be reflected until the next time something triggers the digest loop.

For this you can use $apply:

$apply() is used to execute an expression in angular from outside of the angular framework. (For example from browser DOM events, setTimeout, XHR or third party libraries). Because we are calling into the angular framework we need to perform proper scope life cycle of exception handling, executing watches.

Example:

var onButtonClick = function () {
  scope.$apply(function () {
    // Do something
  });
};
like image 123
tasseKATT Avatar answered Nov 05 '22 03:11

tasseKATT