7

People seem to be against the use of jQuery from the Angular controller. Why??

Suppose you have:

<div id="test">{{test}}</div>
<button class="btn" ng-click="foo()">test</button>

and

.controller('testCtrl', function($scope, $http, $state){

    $scope.test = 'this is the test scope';

    $scope.foo = function(){

        angular.element("#test1").toggle(300);      
    }

}) 

That is a..

  • simple
  • native
  • fast
  • clean
  • readable
  • logically sound

..way to manipulate the DOM.

Plus, you're taking Angular's powerful framework and incorporating tried and true technology and we all know and love. (at least I do)

People say that directives should be used for DOM manipulation, but directives are complex and less readable. Plus, youre telling me that I have to write a custom directive every time I want to manipulate the DOM in some new way? Ain't nobody got time for that! Plus, what is 2-way data binding if not DOM manipulation. And what is a controller if not an Class containing properties and methods that pertain to a given view, the use jQuery just being another method of the sort.

I to write code thats clean and consistent with best-practices. Can anyone give me a compelling reason why jQuery in the controller run contrary to that?

yevg
  • 1,846
  • 9
  • 34
  • 70
  • 2
    You don't put any dom methods in controller at all, not just jQuery. A controller has to run before the template is even compiled in order to build the scope object. Put any dom manipulation in directives or components – charlietfl Dec 17 '16 at 21:27
  • Also don't need jQuery for this, could simply use `ng-class` and css animation – charlietfl Dec 17 '16 at 21:28
  • And in the case of elements inside `ng-repeat` or `ng-include` within view, the elements won't exist when controller runs whereas with directive you are assured they exist – charlietfl Dec 17 '16 at 21:36

0 Answers0