我正在尝试在将来的某个时候将所需的指令添加到元素中。在示例中,如果模型字段是脏的,则将元素设为必需。我试图设置所需的属性(有点乐观)我现在正在编译和链接元素并尝试用新元素替换旧元素。
我的元素只是从页面上消失了?我会以正确的方式解决这个问题吗?
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();
});
}
};
});