首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >角属性指令-在当前指令下面添加ng-重复

角属性指令-在当前指令下面添加ng-重复
EN

Stack Overflow用户
提问于 2016-08-08 17:09:02
回答 1查看 503关注 0票数 0

如果我有一个属性指令,例如如下所示:

<select multiple ... ng-model="ctrl.model" custom-directive="ctrl.customModel" />

假设ngModelcustomModel是数组。在指令的代码中,是否有一种方法可以在指令元素下面添加一段html,该元素可以访问指令的作用域并能够引用customModel,以便它最终看起来如下所示:

代码语言:javascript
复制
<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元素)

编辑:(按要求)--以下是如何在指令元素之后添加元素的示例:

代码语言:javascript
复制
{
  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.
  }
}

像这样添加的任何角分量/指令都不能正常工作或根本不起作用。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-08-12 12:31:06

如果您正在向指令中的页面注入新的HTML,并且需要该HTML使用角指令(ng-重复、ng-绑定等),那么您将需要使用$compile服务来从角度上了解新的DOM元素。在您的示例中,您需要将$compile服务插入到指令中,然后按如下方式使用:

代码语言:javascript
复制
 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); 
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/38834925

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档