0

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();
    }
}
5
  • 2
    directives are made for dom manipulation. Commented Apr 30, 2014 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 Commented Apr 30, 2014 at 15:45
  • Do you want to export a dom manipulating function from your directive controller to be called from your controller? Commented Apr 30, 2014 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. Commented Apr 30, 2014 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 ? Commented Apr 30, 2014 at 15:55

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.