将指令添加到现有元素
问题描述:
我正试图在未来某个时间将所需的指令添加到元素。 在该示例中,如果模型字段很脏,则需要使用该元素。 我试图设置所需的属性(有点乐观) 我现在正在编译和链接元素,并尝试用新元素替换旧元素。将指令添加到现有元素
我的元素刚刚从页面中消失? 我正在以正确的方式去做这件事吗?
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();
});
}
};
});
答
您将不得不在您的指令中使用Transclusion
。这将允许你抽出你的内容,追加required
然后编译它。这是一个很好的教程,解释了基本概念:Egghead.io - AngularJS - Transclusion Basics
答
你实际上不需要那么做。角实际上有一个指令ng-required
看到
http://docs.angularjs.org/api/ng.directive:input.text
可以提供一个表达到NG-需要对具有基于表达式NG-模型,它会在需要验证添加到任何领域评估为真。
从文档
ngRequired(可选) -
{string=}
- 添加必需的属性和 需要验证约束到元件时ngRequired 表达式评估为真。当您要将数据绑定到必需的属性时,请使用ngRequired而不是必需的 。
它只是一个例子,问题仍然是如何动态地向现有元素添加指令。感谢所需的指针 – 2013-04-10 02:47:49