Newbie question on angularJS, but don't see analogous case in tutorials having searched.
How do I pass different parameters to individual div instances using the same directive definition? Here I'd expect to see red green blue but instead I see blue blue blue in the HTML. I see the controller is getting called before the link.
http://jsfiddle.net/gradualstudent/Y2bBy/
<!DOCTYPE html>
<html >
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js"></script>
<script>
var app = angular.module('myApp', []);
app.directive("element", function () {
return {
restrict: "A",
template: '<h1>{{type}}</h1>',
link: function (scope, element, attrs) {
scope.type = attrs.element;
console.log("Setting: "+scope.type);
},
controller: function ($scope) {
console.log("Checking: "+$scope.type);
}
};
})
</script>
</head>
<body ng-app="myApp">
<div element="red">1</div>
<div element="green">2</div>
<div element="blue">3</div>
</body>
</html>
all instances of your directive use the same scope and every time the link function is called, it overrides the previously set scope.type. if you create an isolated scope then it will work because each instance of the directive will get its own scope:
app.directive("element", function () {
return {
restrict: "A",
scope: {},
template: '<h1>{{type}}</h1>',
link: function (scope, element, attrs) {
scope.type = attrs.element;
console.log("Setting: "+scope.type);
},
controller: function ($scope) {
console.log("Checking: "+$scope.type);
}
};
})
In the example you have shared, the directives share the parent scope. Since all directive share the same parent scope there is only one variable type available.
The options that you have is to do either
scope:true //Creates new scope for each directive instance
or
scope:{} //as provided by akonsu. Creates an isolated scope.
Just for completeness please spend time on understanding scope prototypal inheritance https://github.com/angular/angular.js/wiki/Understanding-Scopes
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