Janko Janko - 5 months ago 8
AngularJS Question

Inheritance of scope in angular directive

What is the difference between:

scope: true / false

scope: {}

and not define that property in directive?

What impact does it have on inheritance from parent scope?


Answer

Ya, this really confused me too when I first started with Angular 1.x

Scope: false

Means this directive does not get its own scope. So no $scope.$new is called. Which means the scope your directive accesses, is its parent scope. Think of this as sharing the scope.

<div ng-controller="CtrlA">
    <div ng-controller="CtrlB">
        <my-directive></my-directive>
    </div>
</div>

// In this example, the directive code's scope chain looks like this
// $rootScope --> CtrlA scope --> CtrlB scope
// So if our my-directive calls scope.doSomething()
// It looks in CtrlB first to see if that exists, 
// because my-directive doesn't have its own scope
// Then it checks CtrlA, and finally $rootScope
// Standard prototypical inheritance

Scope: true

Means this directive wants its own scope, that inherits from the current scope. $scope.$new is called and sets the current scope as the parent. This is how scope chains work.

<div ng-controller="CtrlA">
    <div ng-controller="CtrlB">
        <my-directive></my-directive>
    </div>
</div>

// In this example, the directive code's scope chain looks like this
// $rootScope --> CtrlA scope --> CtrlB scope --> my-directive scope
// So if our my-directive calls scope.doSomething()
// It looks in my-directive first to see if that exists
// Then it checks CtrlB, CtrlA, and finally $rootScope
// Standard prototypical inheritance

Scope: {}

This is called an isolated scope. An isolated scope is its own scope, without the inheritance chain. The directive is isolated. It can only access parameters handed in (usually attributes on the directive element) and the only way it can send messages it is through callbacks (that are set as attributes as well. beware, these have a funny way of being called)

<div ng-controller="CtrlA">
    <div ng-controller="CtrlB">
        <my-directive></my-directive>
    </div>
</div>

// In this example, the directive code's scope chain looks like this
// my-directive scope
// So if our my-directive calls scope.doSomething()
// It only looks in my-directive to see if that exists