2013-09-25 34 views
5

Im cố gắng để gửi một thông điệp từ bên trong một chỉ thị để điều khiển nó mẹ (không thành công)angularjs: phát sóng từ chỉ thị để điều khiển

Đây là HTML của tôi

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

Đây là mã trong bộ điều khiển mà nghe cho sự kiện

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

Và cuối cùng là chỉ trông giống như

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

Tôi đã thử cấu hình phạm vi khác và $ phát sóng thay vì $ phát ra. Tôi thấy rằng sự kiện bị sa thải, nhưng bộ điều khiển không nhận được sự kiện 'go'. Bất kỳ đề xuất ?

+1

Bạn có sử dụng '$ phạm vi $ trên ('đi', function() {....});.' Hoặc là một lỗi đánh máy ? – kubuntu

Trả lời

20

Không có phương pháp on có phạm vi. Trong góc đó là $on

dưới đây sẽ làm việc cho bạn

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

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

Các vấn đề liên quan