angularjs:从指令广播到控制器

Jea*_*eri 13 dom-events angularjs angularjs-scope angularjs-components

我试图从指令内部向其父控制器发送消息(没有成功)

这是我的HTML

<div ng-controller="Ctrl">
   <my-elem/>
</div>
Run Code Online (Sandbox Code Playgroud)

这是控制器中侦听事件的代码

$scope.on('go', function(){ .... }) ;
Run Code Online (Sandbox Code Playgroud)

最后指令看起来像

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 }) ;
            }
        }
    }
  }) ;
Run Code Online (Sandbox Code Playgroud)

我尝试过不同的范围配置和$ broadcast而不是$ emit.我看到事件被触发,但控制器没有收到'go'事件.有什么建议 ?

Aja*_*wal 26

没有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>
Run Code Online (Sandbox Code Playgroud)