在指令中动态添加 ng-required 属性
Add ng-required attribute dynamically in directive
目前我已经定义了我的自定义指令:
.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
没有被应用。
假设你有一个输入需要扩展,你可以这样做:
<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
}
目前我已经定义了我的自定义指令:
.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
没有被应用。
假设你有一个输入需要扩展,你可以这样做:
<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
}