【问题标题】:How can I dynamically add a directive in AngularJS?如何在 AngularJS 中动态添加指令?
【发布时间】:2013-02-23 03:02:32
【问题描述】:

我对我正在做的事情有一个非常精简的版本,可以解决问题。

我有一个简单的directive。每当您单击一个元素时,它都会添加另一个元素。但是,它需要先编译才能正确渲染。

我的研究使我找到了$compile。但是所有的例子都使用了一个复杂的结构,我真的不知道如何在这里应用。

小提琴在这里:http://jsfiddle.net/paulocoelho/fBjbP/1/

JS 在这里:

var module = angular.module('testApp', [])
    .directive('test', function () {
    return {
        restrict: 'E',
        template: '<p>{{text}}</p>',
        scope: {
            text: '@text'
        },
        link:function(scope,element){
            $( element ).click(function(){
                // TODO: This does not do what it's supposed to :(
                $(this).parent().append("<test text='n'></test>");
            });
        }
    };
});

Josh David Miller 的解决方案: http://jsfiddle.net/paulocoelho/fBjbP/2/

【问题讨论】:

    标签: angularjs angularjs-directive dynamically-generated


    【解决方案1】:

    除了完善Riceball LEE的例子,添加新的element-directive

    newElement = $compile("<div my-directive='n'></div>")($scope)
    $element.parent().append(newElement)
    

    可以使用这种方式向现有元素添加新的 attribute-directive

    假设您希望即时将my-directive 添加到span 元素。

    template: '<div>Hello <span>World</span></div>'
    
    link: ($scope, $element, $attrs) ->
    
      span = $element.find('span').clone()
      span.attr('my-directive', 'my-directive')
      span = $compile(span)($scope)
      $element.find('span').replaceWith span
    

    希望对您有所帮助。

    【讨论】:

    • 不要忘记删除原始指令,以防止超出最大调用堆栈大小错误。
    • 嗨,您能否提供关于我提出的新 API 的想法,以使以编程方式添加指令的过程更简单? github.com/angular/angular.js/issues/6950 谢谢!
    • 我希望在 2015 年我们不会对调用堆栈大小有限制。 :(
    • Maximum call stack size exceeded 错误总是因为无限递归而发生。我从未见过增加堆栈大小可以解决问题的实例。
    • 我遇到了类似的问题,你能帮我看看吗stackoverflow.com/questions/38821980/…
    【解决方案2】:

    乔什·大卫·米勒是正确的。

    PCoelho,如果您想知道 $compile 在幕后做了什么以及如何从指令生成 HTML 输出,请看下面

    $compile 服务编译包含指令(“test”作为元素)的 HTML("&lt; test text='n' &gt;&lt; / test &gt;") 片段并生成一个函数。然后可以使用范围执行此函数以获取“来自指令的 HTML 输出”。

    var compileFunction = $compile("< test text='n' > < / test >");
    var HtmlOutputFromDirective = compileFunction($scope);
    

    此处提供完整代码示例的更多详细信息: http://www.learn-angularjs-apps-projects.com/AngularJs/dynamically-add-directives-in-angularjs

    【讨论】:

      【解决方案3】:

      受之前许多答案的启发,我提出了以下“stroman”指令,它将用任何其他指令替换自身。

      app.directive('stroman', function($compile) {
        return {
          link: function(scope, el, attrName) {
            var newElem = angular.element('<div></div>');
            // Copying all of the attributes
            for (let prop in attrName.$attr) {
              newElem.attr(prop, attrName[prop]);
            }
            el.replaceWith($compile(newElem)(scope)); // Replacing
          }
        };
      });
      

      重要提示:使用restrict: 'C' 注册您要使用的指令。像这样:

      app.directive('my-directive', function() {
        return {
          restrict: 'C',
          template: 'Hi there',
        };
      });
      

      你可以这样使用:

      <stroman class="my-directive other-class" randomProperty="8"></stroman>
      

      要得到这个:

      <div class="my-directive other-class" randomProperty="8">Hi there</div>
      

      专业提示。如果您不想使用基于类的指令,那么您可以将'&lt;div&gt;&lt;/div&gt;' 更改为您喜欢的内容。例如。有一个包含所需指令名称而不是class 的固定属性。

      【讨论】:

      【解决方案4】:

      如果您尝试动态添加使用内联 template 的指令,则 Josh David Miller 接受的答案非常有用。但是,如果您的指令利用templateUrl 他的答案将不起作用。这对我有用:

      .directive('helperModal', [, "$compile", "$timeout", function ($compile, $timeout) {
          return {
              restrict: 'E',
              replace: true,
              scope: {}, 
              templateUrl: "app/views/modal.html",
              link: function (scope, element, attrs) {
                  scope.modalTitle = attrs.modaltitle;
                  scope.modalContentDirective = attrs.modalcontentdirective;
              },
              controller: function ($scope, $element, $attrs) {
                  if ($attrs.modalcontentdirective != undefined && $attrs.modalcontentdirective != '') {
                      var el = $compile($attrs.modalcontentdirective)($scope);
                      $timeout(function () {
                          $scope.$digest();
                          $element.find('.modal-body').append(el);
                      }, 0);
                  }
              }
          }
      }]);
      

      【讨论】:

        【解决方案5】:
        function addAttr(scope, el, attrName, attrValue) {
          el.replaceWith($compile(el.clone().attr(attrName, attrValue))(scope));
        }
        

        【讨论】:

          【解决方案6】:

          在angularjs上动态添加指令有两种风格:

          将 angularjs 指令添加到另一个指令中

          • 插入新元素(指令)
          • 向元素插入新属性(指令)

          插入新元素(指令)

          这很简单。你可以在“链接”或“编译”中使用。

          var newElement = $compile( "<div my-diretive='n'></div>" )( $scope );
          $element.parent().append( newElement );
          

          向元素插入新属性

          很难,两天就让我头疼。

          使用“$compile”会引发严重的递归错误!!也许它应该在重新编译元素时忽略当前指令。

          $element.$set("myDirective", "expression");
          var newElement = $compile( $element )( $scope ); // critical recursive error.
          var newElement = angular.copy(element);          // the same error too.
          $element.replaceWith( newElement );
          

          所以,我必须找到一种方法来调用指令“链接”函数。很难获得隐藏在闭包内部的有用方法。

          compile: (tElement, tAttrs, transclude) ->
             links = []
             myDirectiveLink = $injector.get('myDirective'+'Directive')[0] #this is the way
             links.push myDirectiveLink
             myAnotherDirectiveLink = ($scope, $element, attrs) ->
                 #....
             links.push myAnotherDirectiveLink
             return (scope, elm, attrs, ctrl) ->
                 for link in links
                     link(scope, elm, attrs, ctrl)       
          

          现在,它运行良好。

          【讨论】:

          • 如果可能的话,我很想看到在原版 JS 中向元素插入新属性的演示 - 我错过了一些东西......
          • 向元素插入新属性的真实例子在这里(见我的github):github.com/snowyu/angular-reactable/blob/master/src/…
          • 老实说没有帮助。这就是我最终解决问题的方式:stackoverflow.com/a/20137542/1455709
          • 是的,这种情况是将一个属性指令插入另一个指令,而不是在模板中插入元素。
          • 在模板之外这样做的原因是什么?
          【解决方案7】:

          你有很多毫无意义的 jQuery,但在这种情况下,$compile 服务实际上是超级简单

          .directive( 'test', function ( $compile ) {
            return {
              restrict: 'E',
              scope: { text: '@' },
              template: '<p ng-click="add()">{{text}}</p>',
              controller: function ( $scope, $element ) {
                $scope.add = function () {
                  var el = $compile( "<test text='n'></test>" )( $scope );
                  $element.parent().append( el );
                };
              }
            };
          });
          

          您会注意到我也重构了您的指令以遵循一些最佳实践。如果您对此有任何疑问,请告诉我。

          【讨论】:

          • 太棒了。有用。看,这些简单和基本的例子应该在 angulars 的文档中显示。他们从复杂的例子开始。
          • 谢谢,乔希,这真的很有用。我在 Plnkr 中制作了一个工具,我们在新的 CoderDojo 中使用它来帮助孩子们学习如何编码,我只是对其进行了扩展,以便我现在可以使用 Angular Bootstrap 指令,如 datepicker、alert、tabs 等。显然我搞砸了一些事情现在它只在 Chrome 中工作:embed.plnkr.co/WI16H7Rsa5adejXSmyNj/preview
          • Josh - 在不使用 $compile 的情况下,有什么更简单的方法来完成此任务?顺便谢谢你的回答!
          • @doubleswirve 在这种情况下,使用 ngRepeat 会容易得多。 :-) 但我假设您的意思是向页面动态添加新指令,在这种情况下答案是否定的 - 没有更简单的方法,因为 $compile 服务是将指令连接起来并将它们挂钩到事件循环中。在这种情况下,$compileing 是没有办法的,但在大多数情况下,像 ngRepeat 这样的另一个指令可以完成同样的工作(所以 ngRepeat 正在为我们进行编译)。你有具体的用例吗?
          • 编译不应该发生在预链接阶段吗?我认为控制器应该只包含非 DOM、可单元测试的代码,但我对链接/控制器概念不熟悉,所以我不确定自己。此外,一个基本的替代方案是 ng-include + partial + ng-controller,因为它将充当具有 inherited 范围的指令。
          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-05-08
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-12-18
          相关资源
          最近更新 更多