【问题标题】:How can I set the ng-change attribute on some mark up inside my custom directive?如何在自定义指令中的某些标记上设置 ng-change 属性?
【发布时间】:2015-12-18 11:35:54
【问题描述】:
我有一个自定义指令,其中包含一个 <select> 和一个 <input>。
如果我输入<my-custom-directive ng-change="vm.someFunction()">,如何将ng-change 添加到指令模板中标记内的<select>?
【问题讨论】:
标签:
javascript
angularjs
angularjs-directive
【解决方案1】:
您可以使用 '&' 将函数传递到指令的作用域。因此,当您定义指令时,请通过以下方式指定范围:
scope: {
'myChangeFunction' : '&'
}
您可以在模板中使用它
<select ng-change="myChangeFunction()">
在您的客户端代码中,您可以指定:
<my-custom-directive my-change-function="vm.someFunction()">
【解决方案2】:
如果我没有误解您的问题,您希望将指令 ng-change 添加到指令模板内的 select 中。只需将 ng-change 添加到 select 并在指令的控制器中处理事件。
指令模板:
<select ng-model="model.id" ng-change="selectChange()">
<option value="0">Zero</option>
<option value="1">One</option>
<option value="2">Two</option>
指令:
app.directive("testDirective", function(){
return{
restrict: 'E',
templateUrl: 'testDirective.html',
controller: function($scope){
$scope.selectChange = function(){
console.log('select change!');
}
}
}
})
看看这个笨蛋。
http://plnkr.co/edit/U184Z8rSjxa6NFEw0n4t?p=preview