0

Method 1

In HTML:

<my-directive>
</my-directive>

In Scripts:

function myDirective() {
    var ddo = {
        [LOTS OF OTHER VERY IMPORTANT DIRECTIVE PROPERTIES HERE]
        controller: myController
        bindToController: true
    };
    return ddo;
}

Method 2

In HTML:

<my-directive ng-controller="myController">
</my-directive>

In Scripts:

function myDirective() {
    var ddo = {
        [LOTS OF VERY IMPORTANT DIRECTIVE PROPERTIES HERE]
    };
    return ddo;
}

Both cases there is a directive with some other properties (template, etc.) but I am just changing where I put controller. Are the two methods analogous?

Facundo La Rocca
  • 3,786
  • 2
  • 25
  • 47

1 Answers1

1

No, first method is preferred.

Difference is in how angular treats scopes.

Second method makes directive dependent on external scope (created by ng-controller="myController") which is against the point of creating directive (code isolation).

Second method will work the same when you use parents scope (by default, when you don't set scope property in directive DDO - Ref: What is default Angular directive scope)

Second method won't work if you have isolated scope in directive, created like this:

scope: {
    param1: "="
}

As you won't be able access properties from myController.


Edit:

Directives rules might be complicated to understand all cases, consider using .component() as it has much simpler and follows best practices - Introduction to Angular's components.


Further reading:

Community
  • 1
  • 1
Piotr Lewandowski
  • 6,540
  • 2
  • 27
  • 32
  • Thanks, just what I needed! – user7339019 Dec 30 '16 at 15:14
  • One more follow up, does this mean that there is a difference between creating a directive with *no* scope attribute versus creating it with the scope attribute set to an empty object? – user7339019 Dec 31 '16 at 07:10
  • @user7339019 - yes, `scope` parameter tooks two values, true/false or object. If there is object (even empty) scope is isolated and you cannot access properties from parents scopes. If `scope` is set to false or just skipped in DDO, directive doesn't create new scope. – Piotr Lewandowski Jan 01 '17 at 11:13