我尝试使用$broadcast
从控制器调用指令方法。
但是,只有按下按钮两次才能抓住事件。
我错过了什么吗?
以下是代码片段:
HTML
<div ng-controller="MainCtrl">
<test-dir name="{{test}}"></test-dir>
<select ng-model="broadcastTo" ng-options="x as x for x in ['test1', 'test2', 'test3']"></select>
<button ng-click="broadcastToSelectedChild()">test</button>
</div>
JS
var app = angular.module('angularjs-starter', []);
app.controller('MainCtrl', function($scope) {
// a method that broadcasts to a selected child.
$scope.broadcastToSelectedChild = function (){
$scope.test = $scope.broadcastTo;
console.log('call-' + $scope.test);
$scope.$broadcast('call-' + $scope.test);
};
});
app.directive('testDir', function (){
return {
restrict: 'E',
scope: {
'name': '@'
},
template: '<div>{{name}} called: {{called}}</div>',
link: function(scope, elem, attr) {
scope.called = false;
//set up the name to be used as the listened to event.
var eventOn;
scope.$watch('name', function(v) {
console.log('listen ..','call-' + scope.name);
if(eventOn){
eventOn();
}
eventOn = scope.$on('call-' + scope.name, function (){
alert(scope.name);
});
});
}
};
});
从HERE
中取出示例谢谢,
答案 0 :(得分:1)
它不起作用,因为您将指令范围的name
绑定到控制器范围的test
,但ng-model
上的<select>
绑定到broadcastTo
。当您从<select>
中选择一个值时,test
未更新,并且您的指令中的$ watch不会触发以附加事件处理程序。
尝试:
<test-dir name="{{broadcastTo}}"></test-dir>
在您的代码中,您必须单击两次,因为第一次单击更新test
并导致$ watch触发以附加事件处理程序:
$scope.test = $scope.broadcastTo;
第二次点击将能够处理来自您的控制器的广播事件。