Directives scope in AngularJS

Scope is context where the model is stored so that controllers, directives and expressions can access it. By default, each directive inherits its parent’s scope, which is passed to it in the link function. below three options are described scope creation in angularjs,

Scope:false (default) which basically tells AngularJS that the directive scope is the same as the parent scope.
Example: If scope:false means it will simply return same address location of parent scope.
working Fiddle.

return {
    restrict: 'A',
      scope:false,
    template: '',
    link: function(scope, element, attrs) {
        console.log(scope);
        scope.data = scope.data + " + directive postfix";
        child = scope;
    }

Result:

 image01

Scope:true creates new scope object but never override parent properties. The directive thus gets access to all the variables and functions from the parent scope, but any modifications it makes are not available in the parent.
Example: create a child scope prototypically inherited with scope: true.
working Fiddle.

return {
    restrict: ‘A’,
      scope:true,
    template: ”,
    link: function(scope, element, attrs) {
        console.log(scope);
        scope.data = scope.data + ” + directive postfix”;
        child = scope;
    }

Result:

image00

Scope:{} (isolated scope) This scope does not inherit anything from the parent, and any data that the parent scope needs to share with this directive needs to be passed in through HTML attributes
Example: create an isolated scope with scope: {} then you can bind some property to parent scopes with ‘@’, ‘&’, ‘=’.
working Fiddle.

return {
    restrict: ‘A’,
      scope:{},
    template: ”,
    link: function(scope, element, attrs) {
        console.log(scope);
        scope.data = scope.data + ” + directive postfix”;
        child = scope;
    }

Result:

image02

Leave a Reply

Your email address will not be published. Required fields are marked *