我正试图在未来某个时间将所需的指令添加到元素。 在该示例中,如果模型字段很脏,则需要使用该元素。 我试图设置所需的属性(有点乐观) 我现在正在编译和链接元素,并尝试用新元素替换旧元素。将指令添加到现有元素
我的元素刚刚从页面中消失? 我正在以正确的方式去做这件事吗?
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-04-10 02:47:49