Passign data to directive with $broadcast and Service in AngularJS

831 views Asked by At

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

3

There are 3 answers

0
georgeawg On BEST ANSWER

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.

2
Michal Kucaj On

YOu can try this solution:

<button onclick="_ajaxCUSTOMER('foo', 'e')" >Send</button>
function _ajaxCUSTOMER(name,obj) {
    angular.element(document).find('body').injector().get('broadcastService').sendAjaxResut(name, obj);
      console.log('ok');
  }

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

    myApp.directive('bill', function () {
    return {
        restrict: 'EAC',
        controller: function($scope) {},
        link: function(scope, element, attrs) {
            scope.$on("newEvent", function(event, data, name, obj) {
              console.log('-- directive')
            });
        }
    };
});
1
Stepan Kasyanenko On

You need define controller in your html.

Live example on jsfiddle.

var app = angular.module('app', [])
  .controller('ExampleController', function($scope, broadcastService) {
  });
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", function($rootScope) {
  return {
    restrict: "E",
    template:'<div>My bill</div>',
    link: function($scope) {
      $rootScope.$on("b1", function(e, a) {
        console.log('-- directive',a)
      });
    }
  }
});


function _ajaxCUSTOMER1(e) {
angular.element(document).find('body').injector().get('broadcastService').sendAjaxResut('b1', e);
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body id="app" ng-app="app">
  <div ng-controller="ExampleController">
    <button onclick="_ajaxCUSTOMER1('5')">
      Click Here to send 5
    </button>
    <bill>
    </bill>
  </div>
</body>