14

I am learning AngularJS directive, and one thing I want to do is to pass some variable $scope.message in the parent scope (a scope of a controller), and I want it to be renamed to param inside the directive alert. I can do this with an isolated scope:

<div alert param="message"></div>

and define

.directive("alert", function(){
    return{
        restrict: "A",
        scope: {
            param: "="
        },
        link: function(scope){
            console.log(scope.param) # log the message correctly
        }
    }
})

But can I do this without using isolated scope? Suppose I want to add another directive toast to the <div toast alert></div> and utilize the same param (keeping the 2-way data-binding), naively I will do

.directive("toast", function(){
    return{
        restrict: "A",
        scope: {
            param: "="
        },
        link: function(scope){
            console.log(scope.param)
        }
    }
})

I surely will get an error Multiple directives [alert, toast] asking for new/isolated scope on:<div...

So in all, my question is, how to rename parent scope variable without isolated scope, and how to share variables when two directives are placed on a single DOM?

1
  • Do you want 2 directives to bind to the same parent $scope property? Commented Dec 30, 2014 at 17:37

1 Answer 1

16

Modify your toast directive:

.directive("toast", function(){
    return{
        restrict: "A",
        link: function(scope, elem, attrs){
            var param = scope.$eval(attrs.param);
            console.log(param)
        }
    }
})

Example fiddle.

Since toast is now on the same scope as the parent would have been (if it was allowed to be isolate scope), you can simply call $eval on scope with the param attribute to get the value.

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

3 Comments

Thanks, works perfectly! I should take a look at $eval() docs then.
does the $eval() just return the value or actually provides data-binding? It appears it only return the value, but I want to make sure.
It is just the value. If you need to simulate bindings, you could use a $watch... I believe this can be overkill though as you just have to $eval again to get the most recent value (on some ngEvent for instance).

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.