为什么用$元/控制器中注入? [英] Why is $element available/injected in controller?

查看:128
本文介绍了为什么用$元/控制器中注入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在AngularJS,我注意到一个控制器注入$元素,这是控制器控制的元素的JQuery / JQLite包装。例如:

In AngularJS, I've noticed that a controller is injected with $element, which is JQuery/JQLite wrapper of the element the controller is controlling. For example:

<body ng-controller="MainCtrl">

然后就可以通过注入$元素访问控制器中的主体元素

Then you can have access to the body element in the controller by injecting $element

app.controller('MainCtrl', function($scope, $element) { ...

这可以看出在plunkr工作

This can be seen working at the plunkr

<一个href=\"http://plnkr.co/edit/Z8ob5HlX1xrNd3jdVa3V?p=$p$pview\">http://plnkr.co/edit/Z8ob5HlX1xrNd3jdVa3V?p=$p$pview

和似乎被确认为文档为$故意功能编译

我的问题是:


  • 在各种指南和教程,建议你不要访问DOM在控制器的光,这是为什么甚至可能吗?

  • In the light of the various guides and tutorials that suggest you shouldn't access the DOM in a controller, why is this even possible?

有任何非哈克的用例?

是否有可用code使用任何的例子地方?

Are there any examples of this being used in available code somewhere?

感谢。

推荐答案

无论你注入$元素与否,控制器的范围约束,且元素。

In the light of the various guides and tutorials that suggest you shouldn't access the DOM in a controller, why is this even possible?

Whether you inject $element or not, the controller's scope is bound on that element.

angular.element('#element-with-controller').scope();

角围绕指令。这就是在MVC的东西胶合在一起。
如果你仔细想想,NG-控制器,是一种指令本身。

Angular revolves around directives. It's what glues things together in the MVC. And if you think about it, ng-controller, is a directive itself.

我想这可以派上用场,当你使用多个指令单个控制器。

I guess this can come in handy when you're using a single controller for multiple directives.

.controller('MyController', function($scope, $element){
    $scope.doSomething = function(){
        // do something with $element...
    }
})
.directive('myDirective1', function(){
    return {
        controller: 'MyController'
    }
})
.directive('myDirective2', function(){
    return {
        controller: 'MyController'
    }
})

每个指令都会有指定的控制器的新实例,但基本上分享它的属性,依赖关系。

Each directive will have a new instance of the assigned controller, but basically share it's properties, dependencies.

我写了一个表单处理程序控制器一次,注册/登录/联系我们等。

I wrote a form handler controller once, for registration/login/contactus, etc.

这篇关于为什么用$元/控制器中注入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆