2

I put the init() function outside of the return of my directive :

app.directive('myDirective', function()
{
    return {
        restrict: 'C',
        controller: function($scope)
        {
            init($scope);
        }
    }

    function init($scope) 
    {
        $scope.params = [];

        // Other initializations
    }
});

Is this bad practice or a bad idea? I just don't like to have the init() inside the controller since I feel that things inside the controller are meant to be reused and run continuously.

One of my reasoning for putting it at the end is that initialization happens once, and I want to place it at the very bottom of the code, where it doesn't bother me, and doesn't steal space from my other code that I spend more time on.

What do you think/suggest?

7
  • 2
    Its a matter of preference. Breaking up a bigger function so that it calls sub-functions through divide and conquer is a good strategy. Personally, I would prefer to put the init function inside of the controller function (limit the scope and move it so that it is closer to where it is used) Commented Jul 23, 2014 at 7:00
  • @micronyks, can you please explain why? Commented Jul 23, 2014 at 7:01
  • @micronyks Why, please? Commented Jul 23, 2014 at 7:01
  • @pixelbits, okay that makes sense. For me there are two reasons why I want it out: 1. I don't like indentation. 2. Initialization happens once, and it is the simple thing. I want to put it at the very bottom of the page as to not worry about it Commented Jul 23, 2014 at 7:02
  • @Kousha why not do the initialization in a link-function? Commented Jul 23, 2014 at 7:04

1 Answer 1

4

I've seen patterns similar to yours many times, don't worry too much about it. The only thing I would change is moving the initialization to the link function; the controller in directives is used to expose an API to other directive (used through require), so I wouldn't mix it with other stuff. I try to keep the API/communication part clean and initialize/bind stuff in the link function.

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

1 Comment

Thanks, and haha sorry but your name is link, and you prefer the link :p. I voted your answer for the explanation!

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.