pro.mean pro.mean - 5 months ago 16
AngularJS Question

how to access controller dataset in custom directive

I was playing with angular js scope of custom directive and tried to use controller dataset in custom directive with different attribute name but did not succeed. Kindly see my code and suggest me what is the proper way to access the data and set in

ng-repeat
in custom directive.

Do I need to set ng-repeat on custom directive or inside the directive template ? I mean

like this

<movie-list ng-repeat="entry in movieData" > </movie-list>


or inside directive template

<movie-list movieArray = "movieData" ></movie-list>


and then

<div>
<ul >
<li ng-repeat="entry in movieArray"> {{...}} </li>
</ul>
</div>


here is my data

app.js



angular
.module('app')
.controller('homeController', function($scope) {
$scope.movieData = [{
name : 'PK',
star : 'Aamir Khan',
releaseYear : '2015'
},
{
name : 'PiKu',
star : 'Irrfan Khan',
releaseYear : '2015'
}
];
});

// custom directive

angular
.module('app')
.directive('movieList', function(){
// Runs during compile
return {
scope: { movieArray : '=movieArray' },
controller: function($scope, $element, $attrs, $transclude) {
},
require: '?ngModel',
restrict: 'E',
templateUrl: 'movie.html',
replace: true,
link: function($scope, element, attr, controller) {
// console.log($scope.$parent);
}
};
});


index.html



<div ng-controller="homeController" >
<div class="col-lg-6">
<movie-list movieArray="movieData"></movie-list>
</div>


movie.html



<div>
<ul class="list-group" >
<li ng-repeat="entry in movieArray" class="list-group-item" >
<h3 class="list-group-item-heading">{{ entry.name }}</h3>
<p class="list-group-item-text">
{{ entry.star }} - Release in {{ entry.releaseYear }}
</p>
</li>
</ul>
</div>


scope: { movieArray : '=movieArray' }
>> not working

scope: { movieArray : '=movieData' }
>> not working

even I changed the attribute

<movie-list movieArray="movieArray"></movie-list>


but not working

Answer

Update attribute name:

<movie-list movieArray="movieData"></movie-list>

To:

<movie-list movie-array="movieData"></movie-list>

Note: Directive or attribute name should be lower case.