我想返回包含对象数组的范围变量的值长度。好吧,我的想法是减少html视图并将变量存储在我的控制器中。问题是当我在控制台中调用值时,我总是得到长度为0.
以下代码考虑了上一个视图:
<div class="panel panel-default">
<div class="panel-body bg-form">
<div class="col-sm-4">
<strong>total:</strong>
</div>
<div class="col-sm-3">
<span class="badge"> {{ nameslist.length }}</span>
</div>
</div>
</div>
<div class="panel panel-default">
<div class="panel-body bg-form">
<div class="col-sm-4">
<strong>filtered:</strong>
</div>
<div class="col-sm-3">
<span class="badge"> {{ filteredNames.length }}</span>
</div>
</div>
</div>
...
<tr ng-repeat="names in filteredNames = (nameslist | orderBy:sortType:sortReverse)" class="show-cursor">
<td>{{ names.fname }}</td>
<td>{{ names.lname }}</td>
</tr>
这些应该是新代码:
<div class="panel panel-default" ng-repeat="sResult in searchResult">
<div class="panel-body bg-form">
<div class="col-sm-4">
<strong>{{ sResult.title }}:</strong>
</div>
<div class="col-sm-3">
<span class="badge"> {{ sResult.content }}</span>
</div>
</div>
</div>
控制:
$scope.nameslist = CrudService.getAllNames();
$scope.searchResult = [
{
title: 'total',
content: $scope.nameslist.length
},
{
title: 'filtered',
content: $scope.filteredNames.length
}
];
服务:
myApp.factory('CrudService', ['ResService',
function (ResService) {
return {
getAllNames: function () {
return ResService.names.query();
},
...
}]);
myApp.factory('ResService', ['$resource', 'baseUrl',
function ($resource, baseUrl) {
return {
names: $resource(baseUrl + '/api/names/:Id/:fname', {
Id: '@Id',
fname: '@fname'
}, {
'update': {
method: 'PUT'
}
}),
...
}]);
如何只返回数组的编号和数组的过滤编号?
答案 0 :(得分:0)
此行不会立即填充对象;
$scope.nameslist = CrudService.getAllNames();
来自angular documentation on $resource:
重要的是要意识到调用$ resource对象方法 立即返回一个空引用(对象或数组取决于 IsArray的)。一旦数据从服务器返回现有数据 引用填充了实际数据。
您需要绑定到视图中的对象$scope.namelist
,或者等到promise被解析,然后在成功回调中分配属性。
一种解决方案如下;
<强>的Javascript 强>
$scope.searchResult = [{
title: 'total',
content: $scope.nameslist // holds a reference to the item returned by CrudService
}]
查看强>
<div class="col-sm-4">
<strong>{{ searchResult.title }}:</strong>
</div>
<div class="col-sm-3">
<span class="badge"> {{ searchResult.content.length }}</span>
</div>