2016-06-21 23 views
4

我有这样的和平代码:如何在ng-repeat中使用组件?

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

而在item.html,有东西像一堆name.firstname.family
所以,问题是,我无法访问,因为范围的name对象事情。

而我很困惑。至少不应该组件继承name

这是我的组件:

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

在这个HTML页面的控制器中是否有变量'$ scope.name'? –

+0

@TimBiegeleisen'item.html'本身没有控制器。但是它的父项'items.html'有一个控制器,它将'names'设置为一个数组。 –

回答

7

下面是一个例子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> 

基本上你所要做的就是使用绑定到你与NG-重复你的组件中访问循环中的数据绑定的东西。

+0

呵呵,有趣!谢谢。 –

0

你必须绑定name到组件。

实施例从Angular Docs

angular.module('heroApp').component('heroDetail', { 
    templateUrl: 'heroDetail.html', 
    controller: HeroDetailController, 
    bindings: { 
    hero: '=' 
    } 
});