何时使用Angular的$元素(When to use Angular's $element)

系统教程 行业动态 更新时间:2024-06-14 17:02:18
何时使用Angular的$元素(When to use Angular's $element)

我见过几个代码示例,其中$ element被注入角度控制器 。 我花了一些时间试图找到任何文件的$元,但没有能够找到任何在angulars官方文档。

什么是$元素服务,我应该什么时候使用它,以及围绕它使用的最佳实践是什么?

I've seen a few code examples where where $element is injected into an angular controller. I've spent some time trying to find any documentation for $element but havent been able to find any in angulars official docs.

What is the $element service used for, when should I use it, and what are the best practices around it usage?

最满意答案

当你向控制器注入$element你会得到一个JQlite包装版本的控制器被调用的元素。 在指令控制器的情况下,它将是指令所附的任何元素。 在我能找到的文档中唯一提到的是在$ compile描述下 。

你可以在下面的例子中看到:

angular.module('myApp', [])
  .controller('testCtrl', function($scope, $element) {
    console.log($element);
  })
  .directive('testDirective', function() {
    return {
      controller: function($scope, $element) {
        console.log($element);
      }
    }
  }) 
  
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<body ng-app="myApp">
  <div ng-controller="testCtrl" id="controller">Controller</div>
  <div test-directive id="directive">Directive</div>
</body> 
  
 

最好的做法是,除了在指令中,甚至更通常在链接函数中,您不要进行任何DOM更改。 在这种情况下,您几乎不希望在控制器中使用$element ,因为这很可能意味着您从错误的角度接近解决方案。

When you inject $element into a controller you get a JQlite wrapped version of the element that the controller is called from. In the case of a directive controller, it would be whatever element the directive is attached to. The only mention in the docs I could find was under the $compile description.

You can see that in the following example:

angular.module('myApp', [])
  .controller('testCtrl', function($scope, $element) {
    console.log($element);
  })
  .directive('testDirective', function() {
    return {
      controller: function($scope, $element) {
        console.log($element);
      }
    }
  }) 
  
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<body ng-app="myApp">
  <div ng-controller="testCtrl" id="controller">Controller</div>
  <div test-directive id="directive">Directive</div>
</body> 
  
 

The best practice is that you don't make any DOM changes except for in a directive and even more specifically typically in the link function. That being the case you almost never want to use the $element in a controller because that most likely means you are approaching the solution from the wrong angle.

更多推荐

$element,I've,angulars,找到,电脑培训,计算机培训,IT培训"/> <meta name=&quo

本文发布于:2023-04-21 18:47:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/dzcp/0e8cc91731ec32ee019190d1928a67bb.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:元素   Angular   element

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!