angularjs:从指令到控制器的广播

angularjs:从指令到控制器的广播,angularjs,angularjs-scope,dom-events,angularjs-components,Angularjs,Angularjs Scope,Dom Events,Angularjs Components,我试图将指令内的消息发送到其父控制器(未成功) 这是我的HTML <div ng-controller="Ctrl"> <my-elem/> </div> 最后,指令看起来像 angular.module('App').directive('myElem', function () { return { restrict: 'E', templateUrl: '/views/my-elem.html',

我试图将指令内的消息发送到其父控制器(未成功)

这是我的HTML

<div ng-controller="Ctrl">
   <my-elem/>
</div>
最后,指令看起来像

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

我尝试了不同的作用域配置和$broadcast,而不是$emit。我看到事件被触发,但控制器没有收到“go”事件。有什么建议吗?

没有关于范围的方法
。在角度上,它是
$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>

var app=角度模块('测试',[]);
应用程序控制器('测试',功能($范围){
$scope.$on('go',函数(){alert('event is clicked')});
});
应用指令(“myElem”,
函数(){
返回{
限制:'E',
替换:正确,
模板:“”,
链接:函数($scope、$element、$attrs){
警报(“123”);
$element.bind('click',函数(){
log(“我们在”);
$scope.$emit('go');
});
}
}
}) ;
$broadcast
$emit
$on
都不推荐使用 不推荐使用scope/rootScope事件总线,这将使迁移到Angular 2+更加困难

为了简化到AngularJS 2+的转换,AngularJS 1.5引入了:

app.component(“myElem”{
绑定:{
翁戈:"和",,
},
模板:`
点击进入
`,
控制器:函数(){
this.go=(事件、数据)=>{
this.onGo({$event:event,$data:data});
};
}
});
用法:

<div ng-controller="Ctrl as $ctrl">
   <my-elem on-go="$ctrl.fn($data)></my-elem>
</div>

update={{$ctrl.update}


要获取
{nr:10}
您应该向侦听器添加两个参数:
事件
数据

$scope.$on('go', function(event, data){ 
  alert(JSON.stringify(data));
});
(请记住,我们在
上使用
$,而不是在
上使用


您是否使用了
$scope.$on('go',function(){….})还是打字错误?这种事件沟通方式已经过时了。请参阅。结束标记
是错误的HTML。
$scope.$on('go', function(event, data){ 
  alert(JSON.stringify(data));
});