3

Here is my Code:

// HTML

<body>
  <h1>{{foo.name}}</h1>

  <my-directive></my-directive>
</body>

// Scripts

app.directive('myDirective', function() {
return {
    restrict: 'E',
    replace: true,
    scope: true,  //**********
    template: '<h4>{{foo.name}}</h4>',
    controllerAs: 'foo',
    controller: fooCtrl,
    link: function(scope) {
        console.log(scope);
    }
}
});

var fooCtrl = function() {
    this.name = 'FOO';
}

My Question:

If I use controllerAs syntax and don't set scope: true in myDirective, the controller will become global, so the controller will insert foo.name into Tag. But once I set the scope as true, the controller will only apply on myDirective.

How could this happened? Does a controller inside directive create a new scope that inherits from the surrounding scope? Why it will apply on global?

UPDATE

This is a very silly question, as I always use isolate scope before, so forget about the usage of scope inside directive, read the docs and clearly understand. Thanks for answer

2 Answers 2

5

I guess your are asking regarding the scope property in Angular Directives. Also I presume you mean $rootScope by term 'global'. As explained in this guide, In a directive, scope property behaves as follows,

scope.false

The default option which does not create a new scope for a directive but shares the scope with its parent

scope.true

Creates a new scope but prototypically inherits from the parent scope.

scope: ‘isolate’

Creates an isolated scope which does not prototypically inherit from the parent scope but you can access parent scope using scope.$parent

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

Comments

3

Check out the directive documentation and scroll down a bit to the part about the scope option. Setting scope to true creates a new scope that the controller is attached to. Not setting scope defaults it to false, which causes the directive to use the parent scope. That's why the controller is being attached to the parent scope.

1 Comment

Thanks, Jon. I was keep thinking that inside the directive, controller will only apply on it's scope, set scope to true just create a 'child' scope under the directive's scope. >.<

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.