2

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.

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

2 Comments

For the plunk, better the scope is created outside the directive. (Plunk updated highlighting the use-case, for anyone that cares.) Still, this answers the question. Who* says angular doc is bad? * I do.
So in theory, can you compile a new directive (which has some functions on it's scope) by another directive using something like $compile('<test></test>')($rootScope.$new(true); ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.