Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I properly implement DOM manipulation in Angular?

I have recently been assigned to take over and clean up an Angular project that is already complete and in production. This is my first time using Angular.

Everything I've read so far on Angular...

  • https://www.airpair.com/angularjs/posts/top-10-mistakes-angularjs-developers-make
  • http://nathanleclaire.com/blog/2014/04/19/5-angularjs-antipatterns-and-pitfalls/
  • http://kirkbushell.me/when-to-use-directives-controllers-or-services-in-angular/

...Seem to all say the same thing about an Angular app's architecture. Most notably that:

Controllers should never do DOM manipulation or hold DOM selectors; that's where directives and using ng-model come in.

However, the project I've been assigned seems to completely ignore this. For example, an excerpt from the MenuController:

(function() {
  app.controller('MenuController', function($scope) {
    ...

    $scope.openMenu = function () {
        $('.off-canvas-wrap').addClass('offcanvas-overlap-right');
    };

    ...
  });
}());

Should I move this code (and a lot of other code) to directives? Or should I follow the pattern the application has already established and continue doing DOM manipulation in the controllers?

like image 308
plondon Avatar asked Apr 18 '15 17:04

plondon


2 Answers

Yes. Code that fiddles with the DOM has no business in the angular controller and belongs in a directive.

One other advantage of using angular is that there are many good ready made directives available. So if you are going to refactor things anyways, you may want to see if you can speed things up by using other people's directives.

That said, it sounds like a lot of work. You'll want to inform whoever is paying about this and discuss the pros and cons of refactoring with them.

like image 72
flup Avatar answered Oct 12 '22 23:10

flup


$scope.openMenu = function () {
        $scope.newClass = 'offcanvas-overlap-right';
    };

and in partial

<div class="off-canvas-wrap" ng-class="newClass"></div>
like image 21
vinayakj Avatar answered Oct 12 '22 22:10

vinayakj