我正在尝试在将来的某个时候将所需的指令添加到元素中。在本例中,如果model字段是脏的,则将元素设为必需的。我尝试只设置必需的属性(有点乐观),现在我正在编译和链接元素,并尝试用新元素替换旧的elemenet。
我的元素就这么从页面上消失了?我这样做对吗?
app.directive('requiredIfDirty', function ($compile, $timeout) {
return {
restrict: "A",
require: // element must have ng-model attribute.
'ngModel',
link: // scope = the parent scope
// elem = the element the directive is on
// attr = a dictionary of attributes on the element
// ctrl = the controller for ngModel.
function (scope, elem, attr, ctrl) {
var unsubscribe = scope.$watch(attr.ngModel, function (oldValue, newValue) {
if(angular.isUndefined(oldValue)) {
return;
}
attr.$set("required", true);
$timeout(function () {
var newElement = $compile(elem)(scope);
elem.replaceWith(newElement);
}, 1);
unsubscribe();
});
}
};
});
发布于 2013-09-06 22:50:02
你必须在你的指令中使用Transclusion
。这将允许您拉出内容,将required
附加到它,然后编译它。这是一个很好的教程,它解释了基本概念:Egghead.io - AngularJS - Transclusion Basics
发布于 2013-04-10 04:03:39
你实际上并不需要这样做。Angular实际上有一个指令ng-required
看见
http://docs.angularjs.org/api/ng.directive:input.text
您可以在任何具有ng-model的字段上向ng-required提供一个表达式,它会根据计算结果为true的表达式向其添加所需的验证器。
从文档中
true ngRequired(optional) -
-当ngRequired表达式的计算结果为true时,向元素添加必需的属性和必需的验证约束。如果要将数据绑定到所需的属性,请使用ngRequired而不是required。
https://stackoverflow.com/questions/15910920
复制相似问题