distante distante - 1 month ago 16
AngularJS Question

What will be the AngularJS equivalent of jQuery's .bind() / .trigger()

I have this trigger / bind code:

service:

$('body').trigger('ready');


directive:

$('body').bind("ready", function(){
alert("Ready was triggered");
});


Can I do the exact same thing only using angular? If yes, how?

Answer

You need to use events in AngularJS check the below sample example I hope it will be of help to you, please check this article for more information on $emit, $on and $broadcast event system in AngularJS

angular
  .module('demo', [])
  .controller('DefaultController', DefaultController)
  .factory('helloService', helloService)
  .directive('hello', hello);
  
  function DefaultController() {
    var vm = this;
  }
  
  helloService.$inject = ['$rootScope'];
  
  function helloService($rootScope) {
    var service = {
      sendHello: sendHello
    };
    
    return service;
    
    function sendHello() {
      $rootScope.$broadcast('helloEvent', 'Hello, World!');
    }
  }
  
  hello.$inject = ['$rootScope', 'helloService'];
  
  function hello($rootScope, helloService) {
    var directive = {
      restrict: 'E',
      scope: {
      	message: '='
      },
      link: linkFunc
    }
    
    return directive;
    
    function linkFunc(scope, element, attrs, ngModelCtrl) {
      scope.$on('helloEvent', function (event, data) {
        element.text(data);
      });

      sendHello();

      function sendHello() {
        helloService.sendHello();
      }
    }
  }
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="demo">
  <div ng-controller="DefaultController as ctrl">
    <hello></hello>
  </div>
</div>

Comments