2013-09-25 63 views
5

我试着从一个指令中发送消息到其父控制器(没有成功)angularjs:从指令广播到控制器

这里是我的HTML

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

这里是在控制器代码该侦听事件

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

最后的指令看起来像

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 }) ; 
      } 
     } 
    } 
    }) ; 

我试过不同的范围配置和$广播,而不是$发射。我发现事件被解雇了,但控制器没有收到'go'事件。有什么建议么 ?

+1

你使用工作'$范围在$(“走”,函数(){...});'或者是一个错字? – kubuntu

回答

20

有范围没有方法on。在角是$on

下面

应该为你

<!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> 
+0

不错,thnx([jsfiddle](http://jsfiddle.net/Kvt4s/)) –