我一直在学习 Angular,特别是 $filter('filter') 函数以及如何将本地函数作为过滤器函数传递给它。
API(json 文件)包含 trips.json 中的所有行程以及 user.trips.json 中用户已参加过的所有行程的 id 数组。
获取数据的工厂如下所示:
app.factory("tripsApi", function ($http) {
return {
allTrips: $http.get('/api/trips.json')
.success(function (response) {
return response;
})
.error(function (error) {
return error;
}),
userTrips: $http.get('api/user.trips.json')
.success(function (response) {
return response;
})
.error(function (error) {
return error;
})
}
});
下一段代码只是一个检索所有用户行程信息的服务。该服务使用工厂来访问 API(在本例中只是 men json 文件)。并且它应该过滤行程信息以仅检索用户使用 id 数组访问过的行程信息。
app.service("trips", function (tripsApi, $filter) {
var self = this;
this.user = {
trips: Array()
};
this.trips = Array();
this.getUserTrips = function () {
self.getAllTrips.then(function () {
tripsApi.userTrips.success(function (response) {
self.user.trips = $filter('filter')
(self.trips, self.containsChild(id, response));
});
});
};
this.getAllTrips = tripsApi.allTrips.success(function (response) {
self.trips = response;
});
this.containsChild = function (id, idsArray) {
if (id != 0 && idsArray != null) {
for (var i = 0; i < idsArray.length(); i++) {
if (idsArray[i] == i)
return true;
return false;
}
}
}
});
但是我无法让它工作。我得到的第一个错误是 self.containsChild(id, response); 中未定义 id
哪里有错误?欢迎任何帮助:)
最佳答案
id问题,调用应该是:
$filter('filter')(self.trips, self.containsChild); // this won’t really work, though, because your `containsChild` function is not properly defined.
其次,这不是一个正确定义的服务。您想要如下所示的内容
app.service('ServiceName', [ '$filter', function ($filter) {
var myInstance = {};
myInstance.containsChild = function (value, index, array) {
};
myInstance.user = . . .;
return myInstance;
}]);
第三,修复您的 containsChild
函数以采用三个参数。第一个是传递给它的值,第二个是索引,第三个是正在过滤的数组。
关于javascript - AngularJs $filter 在服务中使用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37958311/