将来のある時点で、必要なディレクティブを要素に追加しようとしています。例では、モデル フィールドが汚れている場合は、要素を必須にします。必要な属性を設定しようとしましたが(少し楽観的です)、要素をコンパイルしてリンクし、古い要素を新しい要素に置き換えようとしています。
私の要素がページから消えるだけですか? 私はこれを正しい方法で行っていますか?
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();
});
}
};
});