ChatGPT解决这个技术问题 Extra ChatGPT

如何在 AngularJS 中动态添加指令?

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

我有一个简单的 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/


J
Josh David Miller

你有很多毫无意义的 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 服务是将指令连接起来并将它们挂钩到事件循环中。在这种情况下$compile没有办法,但在大多数情况下,像 ngRepeat 这样的另一个指令可以完成相同的工作(因此 ngRepeat 正在为我们进行编译)。您有特定的用例吗?
编译不应该发生在预链接阶段吗?我认为控制器应该只包含非 DOM、可单元测试的代码,但我是链接/控制器概念的新手,所以我不确定自己。此外,一个基本的替代方案是 ng-include + partial + ng-controller,因为它将充当具有继承范围的指令。
S
Sharikov Vladislav

除了完善Riceball LEE添加新元素指令的例子

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

可以使用以下方式向现有元素添加新的属性指令:

假设您希望将动态 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/…
R
Riceball LEE

在 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
是的,这种情况是将属性指令插入另一个指令,而不是模板中的插入元素。
在模板之外这样做的原因是什么?
u
user1212212
function addAttr(scope, el, attrName, attrValue) {
  el.replaceWith($compile(el.clone().attr(attrName, attrValue))(scope));
}

f
ferics2

如果您尝试动态添加使用内联 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);
            }
        }
    }
}]);

H
Hassaan

乔什大卫米勒是正确的。

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

$compile 服务编译包含指令(“test”作为元素)的 HTML ("< test text='n' >< / test >") 片段并生成一个函数。然后可以使用范围执行此函数以获取“来自指令的 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


G
Gábor Imre

受到许多先前答案的启发,我提出了以下“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>

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


我面临类似的问题,你能帮我吗stackoverflow.com/questions/38821980/…
我的天啊。花了 2 天时间才找到这个 $compile ......谢谢朋友......它效果最好...... AJS 你摇滚......