简体   繁体   English

正确过滤控制器中的json数据

[英]Filter json data in controller, the right way

(there are other questions but neither helped me out) (还有其他问题,但都没有帮助我)

Hi, I would like to know if this is the right way to filter the results I get from service where I'm displaying only one result (like a detail). 嗨,我想知道这是否是过滤从服务中获得的结果的正确方法,而我只显示一个结果(如详细信息)。

I know I could use ng-repeat and filter it in the view and that is the cleanest, but I want to have more control over because I will re-use some of the data in the controller for other operations. 我知道我可以使用ng-repeat并在视图中对其进行过滤,这是最干净的方法,但是我想对它进行更多控制,因为我会将控制器中的某些数据重新用于其他操作。

Right now I'm doing this: 现在我正在这样做:

$scope.savedEvents = Event.getPayedEvents(); //gets a list from service

//Goes through entire list and checks for a match   
angular.forEach($scope.savedEvents, function(event) {
    if (event.IdEvent == $stateParams.eventId) {
        $scope.showEvent = event;
    }
});
//now if there is a match I can use $scope.showEvent.eventName etc

Not sure if this would be easier using $filter to return just one event that has correct IdEvent. 不知道使用$ filter仅返回一个具有正确IdEvent的事件是否会更容易。 Or if someone has better solution, please let me know. 或者,如果有人有更好的解决方案,请告诉我。

thanks 谢谢

I don't see any problems with what you have, but you could inject the $filter service and do this one liner: 我没有遇到任何问题,但是可以注入$filter服务并执行以下操作:

$scope.showEvent = $filter('filter')($scope.savedEvents, { IdEvent: $stateParams.eventId });

EDIT: Here is an easy way to resolve the result to a single value from the returned array: 编辑:这是一种将结果解析为返回数组中单个值的简单方法:

var showEvents = $filter('filter')($scope.savedEvents, { IdEvent: $stateParams.eventId });
$scope.showEvent = showEvents && showEvents.length ? showEvents[0] : null;

In CoffeeScript it is a little more concise: 在CoffeeScript中,它更加简洁:

$scope.showEvent = $filter('filter')($scope.savedEvents, { IdEvent: $stateParams.eventId })?[0]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM