kvn
kvn

Reputation: 2300

Inherit a variable in isolated scope from parent scope

Is it possible to access single variable from rootScope in directives isolated scope?

I understand using scope: false will inherit all the properties from parent scope and scope: true will create a new scope by inheriting all the properties from parent scope.

Can we inherit just one property from parent scope so that the directive can be more modular and cleaner.

Here is case I'm referring to.

index.html

<body ng-app="app">
    <header></header>
    <div ui-view=""></div>
</body>

directive.html

<div>Parent prop is {{parentProp}}</div>

directive.js

app.directive('header', function ($rootScope) {
        return {
            templateUrl: "temp.html"
            restrict: 'E',
            scope: {
                parentProp: "@"
            },
            controller: function () {
                ...
            },
            bindToController: true,
            controllerAs: 'header'
        };
    });

app.js

app.run(function ($rootScope) {
        $rootScope.$on('$stateChangeStart', function (event, next, nextParams) {
            $rootScope.parentProp = false;
            if(checkIfParentPropShouldBeTrue()) {
                $rootScope.parentProp = true;
            }
        });
    });

The parentProp property changes with state. Can I bind this property of rootScope to directive's isolated scope and manipulate directive's DOM respectively on every state change?

Upvotes: 0

Views: 585

Answers (1)

Dustin Hodges
Dustin Hodges

Reputation: 4195

When you define an isolate scope on a directive, it gets the values from attributes on the element of your directive. In this case all you should have to do is "pass" parentProp to the directive, e.g. <header parentProp="{{parentProp}}"></header>

This is good because it makes your code more modular like you wanted. You don't have to assume the value is attached to a scope, but can pass in anything from your scope or controller.

After Comment from OP about doing without attributes

Try injecting $rootScope into into your directive's controller and then setting up a watch. I'm not sure this will work with an isolate scope

app.directive('header', function ($rootScope) {
    return {
        templateUrl: "temp.html"
        restrict: 'E',
        scope: {
            parentProp: "@"
        },
        controller: function ($rootScope, $scope) {
            var unbindWatch = $rootScope.$watch('parentProp', function(value){
                $scope.parentProp = value;
            });
            //clean up watch when controller destroyed
            $scope.$on('$destroy', function(){
                unbindWatch();
            });
        },
        bindToController: true,
        controllerAs: 'header'
    };
});

Upvotes: 1

Related Questions