Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS directives - Isolated Scope and Inherited Scope

Tags:

angularjs

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?

like image 792
Anup Vasudeva Avatar asked Nov 01 '22 08:11

Anup Vasudeva


1 Answers

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.

like image 112
Reto Aebersold Avatar answered Nov 11 '22 13:11

Reto Aebersold