我想用angularjs初始化一个过滤列表,我不知道如何访问ng-init变量......
编辑#1:
app.controller("AgreementsController", function($scope, $http, $filter) {
$scope.agreements = [];
$http.get('/api/agreement').success(function(data, status, headers, config) {
$scope.agreements = data.agreements;
$scope.filteredAgreements = $filter('filter')($scope.agreements,
{number: $scope.search});
});
<tbody ng-init="filteredAgreements = (agreements | filter:{number:search})">
<tr ng-repeat="agreement in agreements | filter:{number:search} | limitTo:5">
<td>{{agreement.number}}</td>
</tr>
</tbody>
{{filteredAgreements.length}} <!-- 291 even if I put "65" into the search -->
答案 0 :(得分:1)
你通过AJAX得到agreements
,这意味着当ngInit
指令运行时它们是空的,因此filteredAgreements
也是空的。你必须等到AJAX调用返回。
要在JavaScript中使用角度过滤器,您需要$filter
服务。您使用过滤器的名称调用它以获取过滤器,然后使用要过滤的数据(在您的情况下为agreements
)和所需的参数调用该函数。
app.controller("AgreementsController", function($scope, $http, $filter) {
$scope.agreements = [];
$http.get('/api/agreement').success(function(data, status, headers, config) {
$scope.agreements = data.agreements;
$scope.filteredAgreements = $filter('filter')($scope.agreements,
{number: $scope.search});
});
参考文献: