【发布时间】:2016-08-08 17:09:02
【问题描述】:
如果我有一个属性指令,例如这样的:
<select multiple ... ng-model="ctrl.model" custom-directive="ctrl.customModel" />
假设ngModel 和customModel 是数组。有没有一种方法可以在指令的代码中添加一段 html below 指令元素,该元素可以访问指令的范围并能够引用 customModel 以便在最后它看起来像这样:
<select multiple ... ng-model="ctrl.model" custom-directive="ctrl.customModel" />
<div><!-- this code gets added by the custom-directive directive and uses it's scope -->
<span ng-repeat="item in customDirectiveCtrl.customModel" ng-bind="item.property"></span>
</div>
我知道我可以使用 jqLite 手动添加 html,但是这个 html 无法访问指令范围。我不想将 custom-directive 指令从属性指令转换为元素指令的原因是因为它使得向底层模板元素添加诸如 id、name、required、disabled 等属性变得更加困难(在在这个例子中,一个select元素)
编辑: 按照要求,这是一个如何在指令元素之后添加元素的示例:
{
restrict: 'A',
require: 'ngModel',
scope: { customModel: '=customDirective' },
link: function(scope, element, attrs, ngModel) {
//element.after('<div></div>'); //this adds a div after the directives element
element.after('<div><span ng-repeat="item in customModel" ng-bind="item.property"></span></div>'); //this will add the html in the string, but will not interpret the angular directives within since (i assume) that it is not bound to any scope.
}
}
像这样添加的任何角度组件/指令都将无法正常工作或根本无法工作。
【问题讨论】:
-
您能发布添加该元素的指令的代码吗?您应该能够创建添加的 HTML 的 sn-p 并使用 $compile 服务将其附加到您想要的任何范围。
-
@mcgraphix 我添加了一个在指令元素后添加任意 html 的示例。你的意思是我可以将
$compile注入到我的指令中,并在element.after的结果上使用它来使用指令范围编译表达式? -
select指令是一个不使用范围的元素指令。它不适用于使用隔离范围的属性指令。此外,select指令将ng-model属性用于其自身目的。自定义指令应避免将ng-model属性用于不同目的。 -
您只需要编译新的 HTML。请参阅下面的答案。
标签: javascript angularjs angularjs-directive angularjs-scope