目前我已经定义了自定义指令:
.directive('foo', function () {
return {
restrict: 'A',
require: 'ngModel',
link: function (scope, element, attributes, ngModel) {
scope.isRequired = function () {
return !attributes.disabled; // more complicated test
};
}
};
}])
它的使用方式如下:
<input name="a" type="text" foo ng-required="isRequired" />
<input name="b" type="text" foo ng-required="isRequired" />
<input name="c" type="text" foo ng-required="isRequired" />
是否可以在指令中定义ng-required
属性,而不是在模板中链接isRequired
方法?
预期结果:
link: function (scope, element, attributes, ngModel) {
element.attr('ng-required', function () {
return !attributes.disabled; // more complicated test
});
}
但是,未调用此函数,未应用ng-required
。
答案 0 :(得分:0)
假设你有一个应该扩展的输入,你可以这样做:
<input ng-model="bar" foo />
和你的指令:
.directive('foo', [function () {
return {
restrict: 'A',
scope: {},
template: '<input ng-required="isRequired" />',
controller: ['$scope', '$element', '$attrs', function ($scope, $element, $attrs){
$scope.isRequired = function(){
return !attributes.disabled; // more complicated test
}
}]
};
}]);
您还可以将其他属性绑定到内部范围:
<input ng-model="bar" foo foo-required="somefunction" />
并在你的指令中:
scope: {
requiredCallback: &fooRequired
}