Vignesh Subramanian
Vignesh Subramanian

Reputation: 7289

angularjs rootscope and isolated scope

Below is my html and javascript

<div ng-app="myApp" ng-controller="myCtrl">
  {{firstname}}
  <sample-directive></sample-directive>
</div>

JS

var app = angular.module("myApp", []);
app.run(function($rootScope){
  $rootScope.firstname = "Root scope value"
});
app.controller("myCtrl", function($scope) {

});

app.directive("sampleDirective",function(){
  return{
    template:"<div>{{firstname}}</div>",
    controller:['$scope',sampleDirectiveScope]
  };
});

function sampleDirectiveScope($scope){
  $scope.firstname = "scope value";
};

I am expecting "Root scope value" to be shown in the expression and "Scope value" to be displayed inside the directive tag

Why are both of them displaying Scope value?

Shouldn't the expression {{firstname}} get value from rootscope as I have changed the firstname only inside the directive's controller?

FIDDLE

Upvotes: 0

Views: 387

Answers (3)

J.P.
J.P.

Reputation: 5763

The $scope of a directive by default points to the scope of whatever is above it. Use the scope property to adjust this.

var app = angular.module("myApp", []);
app.run(function ($rootScope) {
    $rootScope.firstname = "Root scope"
});
app.controller("myCtrl", function ($scope) {
    $scope.lastName = "Doe";
});

app.directive("sampleDirective", function () {
    return {
        template: "<div>{{firstname}}</div>",
        scope: {}, // isolated scope
        controller: ['$scope', sampleDirectiveScope]
    };
});

Using scope: {} provides an isolated scope, separated from the scope above. Within the {}, you can supply a list of properties you want to explicitly get passed in. Other possible values for scope: false (the default, point to scope above) and true (point to above scope through prototyping).

More here: https://docs.angularjs.org/guide/directive (scroll down a bit, or search for "isolate scope")

Upvotes: 2

Saurabh Agrawal
Saurabh Agrawal

Reputation: 7739

use scope: {} in your directive

Upvotes: 1

Philipp Meissner
Philipp Meissner

Reputation: 5482

Sharing the scope is the default behavior of Angular-Directives. For a very detailed and complete answer check this post: https://stackoverflow.com/a/19775531/3686898

Here's your updated fiddle with a new scope:

app.directive("sampleDirective",function(){
  return{
    template:"<div>{{firstname}}</div>",
    scope: {},
    controller:['$scope',sampleDirectiveScope]
  };
});

https://jsfiddle.net/a1gf9fwc/2/

Upvotes: 1

Related Questions