Search code examples
angularjsangularjs-directiveangularjs-scopeangularjs-controller

use a directive with public scope as a isolated scope


Some time ago I have written a custom directive and it is now used at many places inside the code (not possible to change it anymore).

It has a public scope and that was fine until today. Now I want to use the same directive twice inside the same controller-scope (parent-scope) but need each directive (child-scopes) to have its own variables (like isolated-scope) and do not mismatch with each other.

Is it possible to insert this directive and declare explicitly to use an isolated scope, even though it is first created with a public scope? Or maybe a way to restrict it inside the parent-controller? Or is there any other way how to do it?

ex.

// Panel directive
angular.directive('panel', function(){
    return {
        restrict: 'E',
        templateUrl: 'panel.html',
        replace: true,
        transclude: true
    }

});

// Parent directive (include more than one 'panel' directives)
angular.directive('parentDirektive'), function() {
    return {
        restrict: 'E',
        templateUrl: 'parent.html',
        replace: true,
        transclude: true,
        scope: {},
        controller: function($scope) {
            // I want to set different value for this variable
            // in each 'panel' direktive I add in 'parent.html'.
            $scope.headline = 'this.should.be.unique.in.each.panel.directive';
        }
    }
});

parent.html

I want somehow to set the value of 'scope.headline' different for each panel occurence in here (like isolate the variable in each directive)?! But cannot change the scope to isolated in the declaration in need it only in this case.

<html>
    <body>
        <!-- I want to display 'Title: First Panel' -->
        <panel></panel>

        <!-- I want to display 'Title: Second Panel' -->
        <panel></panel>
    </body>
</html>

panel.html

<html>
    <body>
        <h1>Title: {{$scope.headline}}</h1>
    </body>
</html>

Solution

  • One option is to add a controller to each component:

    <html>
        <body>
            <!-- I want to display 'Title: First Panel' -->
            <panel ng-controller="firstPanelController"></panel>
    
            <!-- I want to display 'Title: Second Panel' -->
            <panel ng-controller="secondPanelController"></panel>
        </body>
    </html>
    

    The ng-controller directive creates a new inherited scope on which the controller can place properties that superceed parent scope properties.