我试图从指令中向其父 Controller 发送消息(没有成功)
这是我的 HTML
<div ng-controller="Ctrl">
<my-elem/>
</div>
这是 Controller 中监听事件的代码
$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 }) ;
}
}
}
}) ;
我尝试了不同的范围配置和 $broadcast 而不是 $emit。我看到事件被触发,但 Controller 没有收到 'go' 事件。有什么建议 ?
最佳答案
没有方法on
与范围。在 Angular 是 $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>
关于angularjs:从指令广播到 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19002092/