Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS Directive controllerAs syntax & scope

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

like image 632
Neaped Avatar asked Jul 16 '26 22:07

Neaped


2 Answers

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

like image 75
Tharaka Avatar answered Jul 19 '26 12:07

Tharaka


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.

like image 24
Jon7 Avatar answered Jul 19 '26 12:07

Jon7