【问题标题】:ng-repeat: How to access to the field nameng-repeat:如何访问字段名
【发布时间】:2016-06-11 18:12:25
【问题描述】:
我正在尝试使用嵌套的ng-repeat,在第二个中我需要根据我之前设置的ng-model 进行过滤。但在第二个ng-repeat 内,我需要放置一个取决于字段名称的ng-if。
问题是我尝试使用 (key, value) 形式(效果很好),但是应用过滤器非常烦人。所以我想知道是否有办法访问名称字段。
例如:
<tbody>
<tr ng-repeat="item2 in items2">
<td ng-repeat="val in item2 | filer:blabla" ng-if="val.field != 'foto'">{{val}}</td>
</tr>
</tbody>
【问题讨论】:
标签:
javascript
php
arrays
angularjs
【解决方案1】:
理想情况下,此过滤器代码不应位于您的视图(html 文件)中,而是作为由 ng-show /ng-if function.= 评估的函数位于您的控制器中,该函数将从您的视图中调用。
【解决方案2】:
您最终可以让函数评估结果,并使用Object.keys 获取字段名称并进行比较。
由于 Angular 将遍历对象的值,因此您需要 ng-repeat 的索引来获取实际字段。
在html中:
<tbody>
<tr ng-repeat="item2 in items2">
<td ng-repeat="val in item2 | filer:blabla"
ng-if="shouldBeVisible(item2, $index, 'foto')">{{val}}</td>
</tr>
</tbody>
在控制器中:
$scope.shouldBeVisible = (item, $index, prop)=>{
return Object.keys(item)[$index] !== prop;
}
【解决方案3】:
你可以使用 $index 来访问 val.field
示例:jsfiddle
html
<div ng-app="myApp">
<ul ng-controller="MyCtrl">
<li ng-repeat="item in items">
{{item[0].field}} <!-- just a sanity check -->
<ul>
<li ng-repeat="val in item" ng-if="item[$index].field !== 'apple'">{{val.value}}</li>
</ul>
</li>
</ul>
</div>
代码
angular.module('myApp', [])
.controller('MyCtrl', function($scope){
$scope.items = [
[
{
field: 'apple',
value: 'pie'
},
{
field: 'chocolate',
value: 'cake'
}
]
];
});
【解决方案4】:
感谢解答,我是这样解决的:
<tr ng-repeat="item2 in items2">
<td ng-repeat="ite in item2" >
<img width="50px" ng-if="$index == 0" ng-src="{{ite}}" lazy-src/>
<span ng-if="$index != 0">{{ite}}</span>
</td>
</tr>
因为我以这种方式从数据库中获取数据:
app.controller("getItems2", function ($scope, $http, $rootScope) {
var gi2 = this;
$rootScope.$on("itemClicked",function(event,id){
console.log(id);
gi2.getItems(id);
});
this.getItems = function(idClase){
$http.get('main/getItems2?idClase='+idClase).
then(function (response) {
$scope.columns = [];
response.data.forEach(function(e){
e.Foto = "img/"+e.Foto;
});
$scope.items2 = response.data;
console.log($scope.items2);
}, function (err) {
console.log(err);
// log error
});
};
this.getItems(1);
});