joelkaufman
joelkaufman

Reputation: 21

angularjs directive controller $element

i see angularjs highly suggested not to do any dom manipulation in the controller, only setting the state of the scope, example pulling data from ajax etc,

https://docs.angularjs.org/guide/controller

what about directives controllers with a isolated scope does it make sense to set functions on the isolated scope to do dom manipulation

example

controller:function($scope,$element){
    $scope.editDom = function(){
        $element.someThing();
    }
}

Upvotes: 0

Views: 1291

Answers (2)

Alex Shnayder
Alex Shnayder

Reputation: 1362

Usually I try to split directive logic into pure logic, which goes into controller, and dom manipulation logic which goes into link function.

In cases where I need to put methods which do dom manipulation on scope I declare those functions in the directive link function.

This is some what artificial separation of logic, for which the main driver is writing unit tests as then I can easily write tests that checks the controller.

In cases where my entire logic is dom manipulation and I don't need to expose api to other directives (via require) I don't have controller at all, only link.

Upvotes: 1

phylax
phylax

Reputation: 2086

I'll try an answer with putting the function in a 'private' variable of the directive:

angular.module('...', [])
  .directive('...', function () {
    var
    myDOMManipulations = function (…) {…};

    return {
      scope: {},
      controller: function ($scope) {
        myDOMManipulations(…);
      }
    };
  });

It all depends on what the function needs to do and when it should be called.

Mostly i put even the controller or link function in a private variable so the return { … } gets minimal. For functions it usually doesn't matter where they are defined. Besides if the function shouzld be exported as an API.

Upvotes: 0

Related Questions