我见过几个代码示例,其中$ 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
发布评论