我想构建与普通输入字段具有相同ng-change语法的自定义指令。假设我有一个这样的指令:
;(function() {
'use strict';
angular.module('myMod', []);
angular.module('myMod').directive('myDir', myDirDirective);
function myDirDirective() {
return {
restrict: 'E',
template: '
<input ng-change="checkInput1()" type=...>
<input ng-change="checkInput2()" type=...>
',
controllerAs: 'myDirDirective',
controller: myDirController,
require: 'ngModel',
scope: {},
bindToController: {
model: '='
}
};
}
// Controller goes here...
})(); // EOF
现在我想定义输入检查方法,例如
function checkInput1() {
...
if( <changes in input 1 are legit> ) {
fireOuterNgChange();
}
}
function checkInput2() {
...
if( <changes in input 2 are legit> ) {
fireOuterNgChange();
}
}
最后,我希望能够使用我的自定义指令,例如:
<myDir ng-change="doSomethingAfterSomethingChanged()">
...
</myDir>
一个简单的用例是一个时间选择器,其中有几个输入字段,用于小时:分钟:秒:毫秒。仅举一个例子。我尝试了不同的方法但没有成功;我怎样才能做到这一点?
因此,在这里您需要执行以下两项操作:
<input>
元素上的更改。<my-dir>
。对于(1),您只需按照您说的做即可:您在指令的作用域(scope.checkInput1 = function() { ... }
)中注册回调。
然后,要将事件转发给父对象(最终模仿<input ng-change>
行为),您将需要在指令的隔离范围中声明一个表达式绑定,如下所示:
scope: {
onDateChange: '&'
}
在父控制器上,假设您$scope.onDirectiveDateChange = function() { ... }
在范围中声明了一些,只需将回调传递到自定义指令中,如下所示:
<my-dir on-date-change="onDirectiveDateChange()"></my-dir>
然后从指令的调用它checkInput2
:
scope.onDateChange(); // This will call parent's "onDirectiveDateChange()" if defined
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句