Steven
Steven

Reputation: 2979

angular js: programmatically instantiate a scope?

Simple case: Ask a controller $scope to create a child scope. This new scope would be applied to a $compile's linking function -- i.e. programmatic directive instantiation.

My need falls just outside the scope: true declaration in the directive definition -- I do need a private directive scope but I don't want one created by the framework every time I instantiate the directive. Rather, I'd like to reapply the existing scope to a fresh linkage -- a fresh directive.

IOW, I want to teach a new dog old tricks.

I'm talking about the scope obtained from the compiled directive (see: Retrieving Scopes from the DOM).

Consider the scenario where the HTML representation of the directive (let's call it "half") may move in and out of and around the document. I merely want to save its state (let's call it "the other half") off and reapply it to a fresh half-compiled directive instance.

Scope hierarchy would be respected, i.e. this new directive instance would nestle itself in the same Angular-DOM area as it did in a former life so I don't think any worm holes would be opened nor anti-matter created.

A super-contrived plunk for your viewing pleasure.

Upvotes: 2

Views: 943

Answers (1)

T W
T W

Reputation: 6317

If you want create private scope inside directive you can use scope.$new method like that:

app.directive('colorblock', function ($rootScope) {

    link: function (scope, iElement, iAttrs, controller) {
         var privateScope = $rootScope.$new(true);
    }
   ...
});

It will create isolate scope.

Upvotes: 4

Related Questions