angularjs: broadcast from directive to controller

Jeanluca Scaljeri picture Jeanluca Scaljeri · Sep 25, 2013 · Viewed 14k times · Source

Im trying to send a message from within a directive to its parent controller (without success)

Here is my HTML

<div ng-controller="Ctrl">
   <my-elem/>
</div>

Here is the code in the controller which listens for the event

$scope.on('go', function(){ .... }) ;

And finally the directive looks like

angular.module('App').directive('myElem',
   function () {
    return {
        restrict: 'E',
        templateUrl: '/views/my-elem.html',
        link: function ($scope, $element, $attrs) {
            $element.on('click', function() {
                  console.log("We're in") ; 
                  $scope.$emit('go', { nr: 10 }) ;
            }
        }
    }
  }) ;

I've tried different scope configuration and $broadcast instead of $emit. I see that the event gets fired, but the controller does not receive a 'go' event. Any suggestions ?

Answer

Ajay Beniwal picture Ajay Beniwal · Sep 25, 2013

There is no method on with scope. In angular it's $on

below should work for you

<!doctype html>
<html ng-app="test">
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0-rc.2/angular.js"></script>

  </head>
 <body ng-controller="test" >    
 <my-elem/>

<!-- tabs -->


 <script>
     var app = angular.module('test', []);
     app.controller('test', function ($scope) {

         $scope.$on('go', function () { alert('event is clicked') });
     });
     app.directive('myElem',
   function () {
       return {
           restrict: 'E',
           replace:true,
           template: '<div><input type="button" value=check/></input>',
           link: function ($scope, $element, $attrs) {
               alert("123");
               $element.bind('click', function () {
                   console.log("We're in");
                   $scope.$emit('go');
               });
               }
       }
   }) ;

   </script>
</body>


</html>