如果我有一个属性指令,例如如下所示:
<select multiple ... ng-model="ctrl.model" custom-directive="ctrl.customModel" />
假设ngModel和customModel是数组。在指令的代码中,是否有一种方法可以在指令元素下面添加一段html,该元素可以访问指令的作用域并能够引用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、禁用、.等属性变得更加困难。到基础模板元素(在本例中为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.
}
}像这样添加的任何角分量/指令都不能正常工作或根本不起作用。
发布于 2016-08-12 12:31:06
如果您正在向指令中的页面注入新的HTML,并且需要该HTML使用角指令(ng-重复、ng-绑定等),那么您将需要使用$compile服务来从角度上了解新的DOM元素。在您的示例中,您需要将$compile服务插入到指令中,然后按如下方式使用:
link: function(scope, element, attrs, ngModel) {
//create the new html
var newElement = angular.element('<div><span ng-repeat="item in customModel" ng-bind="item.property"></span></div>');
//compile it with the scope so angular will execute the directives used
$compile(newElement)(scope); //<-this is the scope in your link function so the "customModel" will be accessible.
//insert the HTML wherever you want it
element.after(newElement);
}https://stackoverflow.com/questions/38834925
复制相似问题