gpt4 book ai didi

angularjs:从指令广播到 Controller

转载 作者:行者123 更新时间:2023-12-03 23:17:30 25 4
gpt4 key购买 nike

我试图从指令中向其父 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com