我是AngularJS的新手,目前仍然遇到一个设计问题。提前抱歉,因为这将是啰嗦。
场景#1
我使用了第三方指令(预先输入),该指令公开了一个事件" select"通过$ emit。我需要在预先输入的类型上更新模型"选择"事件反过来驱动一些其他逻辑。
我觉得在父控制器(testController)中处理选定的事件并不理想,因为如果在同一范围内有多个typeahead指令,当我在外面执行此连接时,如何将事件与元素相关联指令?
因此,在模型属性上观察更改(name1)似乎是唯一的干净选项。我对么 ?
<div ng-app="testApp">
<div ng-controller="testController">
<type-ahead ng-model="name1" source="typeAhead1Data"></type-ahead>
<!--<type-ahead ng-model="name2" source="typeAhead2Data"></type-ahead>-->
</div>
</div>
angular.module('testApp').controller('testController', ["$scope", function ($scope) {
$scope.typeAhead1Data = ['abc','def','ghi'];
//$scope.typeAhead2Data = ['jkl','mno','pqr'];
//This seems like a bad idea since what if I had another type-ahead
//control in the scope of the same controller...
$scope.$on('typeahead:selected', function (e, val) {
//logic to be performed on type-ahead select
$scope.name1 = val;
});
/*
// the other approach that came to mind is doing a watch
$scope.$watch('name1', function () {
//logic to be performed on type-ahead select
});
*/
}]);
场景#2
假设我有一个指令,它将菜单添加到无序列表中的每个列表项。 单击菜单项应触发操作。如果指令通过$ emit引发事件,我将遇到将事件与元素相关联并执行必要的后处理的相同问题。
在jquery中,我这样做的方法是在列表项中添加一个类,并使用类selctor附加一个事件。
有什么想法吗?
感谢
答案 0 :(得分:0)
您可以使用scope:true
选项为指令创建子范围,然后将.$on('typeahead:selected')
事件移动到指令的link函数中。这样你就可以为每个指令设置一个单独的事件监听器。