AngularJS directives – Isolated Scope and Inherited Scope

All we need is an easy explanation of the problem, so here it is.

I’ve been trying to understand the difference between isolated scope and inherited scope in directive. This is an example I prepared to make myself understand:

The HTML

<div ng-controller="AppController">
    <div my-directive>
        Inside isolated scope directive: {{myProperty}}
    </div>

    <div my-inherit-scope-directive>
        Inside inherited scope directive: {{myProperty}}
    </div>
</div>

The JS

angular.module("myApp", [])
        .directive("myInheritScopeDirective", function() {
            return {
                restrict: "A",
                scope: true
            };
        })
        .directive("myDirective", function() {
            return {
                restrict: "A",
                scope: {}
            };
        })
        .controller("AppController", ["$scope", function($scope) {
            $scope.myProperty = "Understanding inherited and isolated scope";
        }]);

Executing the code with Angular-1.1.5, it works as I expected: The {{myProperty}} inside my-directive will be undefined because of isolated scope, whereas for my-inherit-scope-directive, {{myProperty}} will have the value Understanding inherited and isolated scope.

But executing with Angular-1.2.1, in both the directives {{myProperty}} outputs Understanding inherited and isolated scope.

Anything I am missing?

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

The text node inside your directive is bound to the controller scope. Therefore the scope of the directive has no effect. I think this has changed as of v1.2. You have to use a template for your directive:

.directive("myIsolatedDirective", function () {
    return {
        template: 'Inside isolated in template scope directive: {{myProperty}}',
        restrict: "A",
        scope: {
            myProperty: '='
        }
    };
})

Check this fiddle.

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply