Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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();
    }
}
share|improve this question
2  
directives are made for dom manipulation. –  phylax Apr 30 at 15:43
    
@phylax i know what directives are made for, the questions is if adding methods to isolated scope to do dom manipulation is good practice –  joelkaufman Apr 30 at 15:45
    
Do you want to export a dom manipulating function from your directive controller to be called from your controller? –  phylax Apr 30 at 15:51
    
Keep it out of the controller. Even if that controller is within a directive, it's still a controller. That being said, you can chain on to the directive. –  tymeJV Apr 30 at 15:51
    
@phylax i want to wrap some dom manipulation logic to be able to call later , where is to place to save this method ? –  joelkaufman Apr 30 at 15:55
add comment

2 Answers

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.

share|improve this answer
add comment

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.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.