Why is $element available/injected in controller?

后端 未结 4 833
盖世英雄少女心
盖世英雄少女心 2020-12-25 11:30

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

4条回答
  •  时光说笑
    2020-12-25 11:41

    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();
    

    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.

    Is there any non-hacky use case for this?

    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.

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

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

提交回复
热议问题