angularjs:从指令广播到控制器 [英] angularjs: broadcast from directive to controller
本文介绍了angularjs:从指令广播到控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试将指令中的消息发送到其父控制器(没有成功)
Im trying to send a message from within a directive to its parent controller (without success)
这是我的HTML
<div ng-controller="Ctrl">
<my-elem/>
</div>
这是控制器中侦听事件的代码
Here is the code in the controller which listens for the event
$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.我看到该事件被触发,但控制器未收到执行"事件.有什么建议吗?
I've tried different scope configuration and $broadcast instead of $emit. I see that the event gets fired, but the controller does not receive a 'go' event. Any suggestions ?
推荐答案
没有具有范围的方法on
.角度为$on
There is no method on
with scope. In angular it's $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:从指令广播到控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文