更新
我想到了一个更好的方法来回答这个问题。旧答案低于新答案。
您可以获得对 AngularJS 的 required 指令的引用并将其应用于您自己的指令。继承人将执行此操作的代码示例:
var myApp = angular.module('myApp', []).directive('valRequired', function(requiredDirective) {
var newDirective = {},
angularDirective = requiredDirective[0]; //This assumes angular's required directive is the first one
//Copy over all other properties of the angular directive
angular.extend(newDirective, angularDirective);
//Change the name of our directive back to valRequired
newDirective.name = 'valRequired';
//Provide our own logic in the linking function
newDirective.link = function(scope, element, attr, ctrl){
//Super call
angularDirective.link.apply(this, arguments);
if(attr.valRequired === 'required'){
attr.$set('ngRequired', 'true');
} else {
attr.$set('ngRequired', 'false');
}
}
return newDirective;
});
<input data-val-required="required" ng-model="foo" />
旧答案
使用 jQuery 或 jQLite 的attr()
方法不会改变AngularJs 的 Attributes object。Attributes 对象是指令用作其逻辑值的对象。
您还需要包含 ng-required 属性,尽管您不需要将任何角度表达式绑定到它。这个问题将帮助你:
Html5 data-* with asp.net mvc TextboxFor html attributes
这样做的原因是我们需要强制 Angular 将指令应用于该节点。在模板的编译阶段之后更新属性不会通知 Angular 将新指令应用于节点。
这应该有效:
var myApp = angular.module('myApp', []).directive('valRequired', function() {
return {
priority : 101, //The priority needs to run higher than 100 to get around angularjs' default priority for ngRequired
link: function (scope, element, attr) {
if(attr.valRequired === 'true'){
attr.$set('ngRequired', 'true');
} else {
attr.$set('ngRequired', 'false');
}
}
};
});
<input ng-required data-val-required="true" ng-model="foo" />