Reputation: 15293
I have the data in the $scope
, according to the scope classNames
count, i require to create elements in the page with different data from the scope
. how to it?
I am trying to add more no.of directive
element, But i see only one output. and i am not able to pass the $scope
data to it.
What is the correct way to do this?
Here is my try:
<div class="wrapper" ng-app="myApp">
<div class="helloWorld" ng-controller="hello">
<ul>
<li ng-repeat="item in items">
{{item.name}}
</li>
</ul>
<hello-world/> //added multiple times
<hello-world/>
<hello-world/>
<hello-world/>
<hello-world/>
</div>
</div>
var app = angular.module('myApp', []);
app.controller('hello', function ($scope) {
$scope.items = [
{name:'name1', className:'green'},
{name:'name2', className:'blue'},
{name:'name3', className:'brown'},
{name:'name4', className:'yellow'},
{name:'name5', className:'red'}
];
});
app.directive('helloWorld', function () {
return {
restrict: 'AE',
replace: 'true',
template: '<h3 class="{item.className}">Hello World!! from color of {{item.className}}</h3>',
scope: {
className: '@'
},
link : function ($scope, elem, attr) {
}
}
});
any one can help me to understand the concept and create the multiple instance of directive here?
Thanks in advance.
Upvotes: 2
Views: 618
Reputation: 7425
..I am trying to add more no.of directive element, But i see only one output.
First of all, you need to close the directive tag properly. Use
So <hello-world><hello-world/>
instead of <hello-world/>
. Also, place the directive in ng-repeat to get multiple elements.
<li ng-repeat="item in items">
{{item.name}}
<hello-world class-name="{{item.className}}"></hello-world>
</li>
and i am not able to pass the $scope data to it.
This is because you have created an 'isolated scope' for your directive!
scope: {
className: '@'
}
The @
sign signifies that the className
in the isolated scope will get its value from the attribute class-name
in the directive
app.directive('helloWorld', function () {
return {
restrict: 'E',
replace: 'true',
template: '<h3>Hello World!! from color of "{{className}}"</h3>',
scope: {
className: '@'
},
link: function ($scope, elem, attr) {}
}
})
Here's the dmeo
Upvotes: 4
Reputation: 193261
The problem is that you didn't close directives properly. Tag directive cannot be self-closable by definition. So what happens when you write <hello-world />
is that the tag remains unclosed and subsequent directives are failed to be parsed.
It should be:
<hello-world></hello-world>
<hello-world></hello-world>
<hello-world></hello-world>
<hello-world></hello-world>
<hello-world></hello-world>
Demo: http://jsfiddle.net/ydkezd15/2/
Upvotes: 1