Mehdi Hoseini Mehdi Hoseini - 5 months ago 57
AngularJS Question

How can I use components with ng-repeat?

I have this peace of code:

<item ng-repeat="name in names"></item>


And in
item.html
, there is bunch of things like
name.first
,
name.family
etc.

So, the problem is, I can't access
name
object because of the scope thing.

And I'm confused. shouldn't the component inheritance
name
at least?

this is my component:

app.component('item', {
templateUrl: '/views/item.html'
});

Answer

Here is an example plnkr:

index.html

  <body ng-controller="MainCtrl">
    <item data="name" ng-repeat="name in names"></item>
  </body>

script.js

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {
  $scope.names = [{family: "asdf", first: "test"}, {family: "qwerty", first: "test2"}]
});

angular.module('plunker').component('item', {
   templateUrl: 'item.html',
   bindings: {
     data: '='
   }
});

item.html

{{$ctrl.data.first}}
{{$ctrl.data.family}}
<br>

Basically what you have to do is use bindings to bind the data you are looping with ng-repeat to access it within your component.