在模板范围内访问DOM——AngularJS

Accessing DOM within template scope - AngularJS

本文关键字:DOM AngularJS 访问 范围内      更新时间:2023-09-26

我对Angular JS很陌生,我处于一种情况,我需要在我的指令模板中选择一些DOM元素(我知道DOM操作在Angular中是不受欢迎的,但在我的情况下,如果没有大量的时间投入,我真的看不到太多的方法……)。问题是我不止一次地使用了我的指令。

下面是一个代码示例来澄清我的意思:

我的index . html。

<html>
  <head> <! necessary script> </head>
  <body ng-app='foo'>
    <my-directive my-attr="someVal"></my-directive>
    <my-directive my-attr="otherVal"></my-directive>
  </body>
</html>

我的JS:

angular.module('foo',[]).directive('myDirective', function() {
  return {
    restrict: 'E',
    templateUrl: 'foo-template.html',
    scope: {},
    replace: true,
    link: function(scope,elem,attrs) {
      //jQuery selector
      scope.bar = angular.element($('.bar').first());
      scope.bar.someFunction(attrs.myAttr);
      function someFunction(message) {
        scope.bar.html(message);
      }
    }
  };
});

My template (foo-template.html):

<p class='bar'></p>

注入后,我的index。html看起来像这样:

<html>
  <body>
    <p class='bar'>otherVal</p>
    <p class='bar'></p>
  </body>
</html>

当我希望它是:

<html>
  <body>
    <p class='bar'>someVal</p>
    <p class='bar'>otherVal</p>
  </body>
</html>

我想限制我对当前被控制的模板内的访问,因为我第二次使用我的指令,它达到第一段并更新它。我认为使用隔离作用域可以解决这个问题,但是它没有。

有谁知道如何实现这一点(或有任何提示如何重构我的代码,使我不必选择DOM元素)?非常感谢!

你已经有了指令链接函数中指定的每个元素的引用:

angular.module('foo',[]).directive('myDirective', function() {
  return {
    restrict: 'E',
    templateUrl: 'foo-template.html',
    replace: true,
    link: function(elem, attrs) {
      elem.html(attrs.myAttr);
    }
  };
});

元素引用已经包含在angular.element中,因此您应该能够在其上使用这些函数。如果需要直接的DOM引用,请使用elem[0]

除非你的例子比你正在做的任何事情都简单,否则我认为你只是以错误的方式接近它。您也可以简单地这样做:

模板:

<p class='bar'>{{message}}</p>

JS:

link: function(scope,elem,attrs) {
  scope.message = attrs.myAttr;
}