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
?
The best way to pass an object to an angular directive is by using the &. When you use &, angular compiles the string as an expression and sets the scope variable in your directive to a function that, when called, will evaluate the expression in the context of the directive's parent's scope.
Isolated scope directive is a scope that does not inherit from the parent and exist on its own. Scenario: Lets create a very simple directive which will show the object from the parent controller.
The $compile service is the service to use for compilation. Invoking $compile against markup will produce a function you can use to bind the markup against a particular scope (what Angular calls a linking function). After linking, you'll have DOM elements you can place into the browser.
All three bindings are ways of passing data from your parent scope to your directive's isolated scope through the element's attributes: @ binding is for passing strings.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With