【问题标题】:Angular attribute directive - add an ng-repeat below current directiveAngular 属性指令 - 在当前指令下方添加 ng-repeat
【发布时间】:2016-08-08 17:09:02
【问题描述】:

如果我有一个属性指令,例如这样的:

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

假设ngModelcustomModel 是数组。有没有一种方法可以在指令的代码中添加一段 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>

我知道我可以使用 jqLit​​e 手动添加 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


【解决方案1】:

如果您在指令中将新 HTML 注入到页面中,并且您需要该 HTML 来使用角度指令(ng-repeat、ng-bind 等),那么您将需要使用 $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); 
}

【讨论】:

    猜你喜欢
    • 2016-07-07
    • 1970-01-01
    • 1970-01-01
    • 2013-10-17
    • 2013-04-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-05
    相关资源
    最近更新 更多