【问题标题】:AngularJS DOM injectionAngularJS DOM 注入
【发布时间】:2015-07-29 01:38:10
【问题描述】:

如果我提前向 AngularJS 注册了一个面向元素的指令,那么我是否可以直接将一个与指令元素匹配的节点(例如 document.appendChild)直接注入到 DOM 中(例如 <my-directive-name my-attribute='foo'></my-directive-name>,AngularJS 会渲染说指令代替它(可能需要手动摘要触发器)?

my-directive-template.html

  <div>
    hello world
  </div>

my-directive-name.js

function MyDirectiveName() {
        return {
            scope: {
              'myAttribute': '&',
            },
            template: template,
            replace: true,
            controller: controller,
            restrict: 'E',
            // ...
        };
}

角度配置:

//...
angular.directive('my-directive-name', require('my-directive-name'))
//...

启动 DOM:

<body></body>

然后我动态追加一个子节点:

<body>
   <my-directive-name my-attribute='foo'>
   </my-directive-name> 
</body>

然后我做一些事情让 Angular 意识到某些事情发生了变化(这是什么?):

结束 DOM:

<body>
   <div>
     hello world
   </div> 
</body>

【问题讨论】:

  • 你能发布简单的例子和​​所需的结果吗?我认为使用ng-if 应该很容易,但我可能不太明白你打算做什么。
  • 这完全没有棱角感。我每天至少评论一篇关于 Angular 说同样的话的帖子。除非在极端情况下,否则操作 DOM 与 angular 的目的背道而驰。在 Angular 中,您应该针对您的数据而不是 DOM 进行编码。
  • 我什至不确定我是否理解您在评论中的要求,但我使用模板和ng-ifng-showng-repeat 等的组合来呈现内容基于大量项目中的数据类型。对于假设的“我不知道它是什么”类型的问题,我无法为您提供解决方案;您为什么不提前知道应用程序流程中的某个地方?毕竟,您不会让用户选择他们想要在页面上呈现的 HTML....

标签: javascript angularjs


【解决方案1】:

在将元素附加到 DOM 之前,您需要确保先 $compile 元素。这是一个简单的示例,展示了如何在 Angular 代码之外(通过 setTimeout)使用 $compile 函数来添加到 DOM。

(function(angular) {

  angular.module('myApp', [])
    .directive('myDirectiveName', MyDirectiveName);

  function MyDirectiveName() {
    return {
      restrict: 'E',
      template: '<div>Custom Directive with {{myAttr}} as my-attribute</div>',
      scope: {
        myAttr: '@myAttribute'
      }
    };
  }

  // run this later.
  setTimeout(function() {

    var appDiv = angular.element(document.getElementById('app'));
    // Get the injector to compile
    var $injector = appDiv.injector();
    var $compile = $injector.get('$compile');
    // compile new elems
    var barLink = $compile(angular.element('<my-directive-name my-attribute="bar"></my-directive-name>'));
    var bazLink = $compile(angular.element('<my-directive-name my-attribute="baz"></my-directive-name>'));

    // append both elements by linking against scope
    appDiv.append(barLink(appDiv.scope()));
    appDiv.append(bazLink(appDiv.scope()));
  }, 3000);
}(angular));
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" id="app">
  <my-directive-name my-attribute="foo"></my-directive-name>
</div>

【讨论】:

    【解决方案2】:

    在追加元素之前,您需要 $compile 。这是一个小提琴:http://jsfiddle.net/ftfish/KyEr3/

    重复问题:Adding a new element into the DOM with angularjs does not initiate it

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-07-17
      • 1970-01-01
      • 2019-02-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多