javascriptangularjsangular-servicesangular-broadcast

Passign data to directive with $broadcast and Service in AngularJS


I'm in the middle of migrating to Angular based front-end. I have a function in JavaScript to pass some data to directive, after some research found that using Service and $broadcast could be a good solution. but doesn't work for me ...

here is my code :

var app = angular.module('app', []);
app.factory('broadcastService', ['$rootScope',
  function($rootScope) {
    var factory = {};
    factory.sendAjaxResut = function(name, obj) {
      console.log(' -- $broadcast ');
      $rootScope.$broadcast(name, obj);
    }
    return factory;
  }
]);

app.directive("bill", [directive]);
function directive() {
  return {
    restrict: "E",
    link: function($scope) {
      $scope.$on("b1", function(e, a) {
        console.log('-- directive')
      });
    }
  }
}

code for passing data to service :

function _ajaxCUSTOMER(e) {
  angular
    .injector(['ng' ,'app']) 
    .get("broadcastService")
    .sendAjaxResut("b1", e);
}

<button onclick="_ajaxCUSTOMER('foo')" >Send</button>

Question 1 : what is ng in .injector(['ng' ,'app'])

Question 2 : at this time console only shows -- $broadcast. what is the problem of my code that can't catching event in directive

jsfiddle


Solution

  • Your directive is not getting the $broadcast because you are creating a new injector with a new $rootScope. Instead use the injector of your app.

    function _ajaxCUSTOMER1(e) {
      var rawElem = document.getElementById("app");
      var elem = angular.element(rawElem);
      var _injector = elem.injector();
      var _broadcastService = _injector.get("broadcastService");
      _broadcastService.sendAjaxResut("b1",e);
    }
    

    This example finds the element of your app and uses angular.element to retrieve its injector.

    The working JSFiddle.