Using Factory and Controller to handle Json

Asked

Viewed 59 times

0

On this website Andrew Mcgivery I found this very interesting example:

.controller('UserCtrl', function($scope, $stateParams, userService) {
        var user = userService.getUser($scope.id);
    })

.factory('userService', function($http) {
    var users = [];

    return {
        getUsers: function(){
            return $http.get("https://www.yoursite.com/users").then(function(response){
                users = response;
                return users;
            });
        },
        getUser: function(id){
            for(i=0;i<users.length;i++){
                if(users[i].id == id){
                    return users[i];
                }
            }
            return null;
        }
    }
})

I would like to know how to return all users if you had more than one user with the same id?

  • C# or Angularjs?

  • C#, but if you manage to pass a little of each I am grateful.

  • But what’s the problem?

  • I want to list all items for a particular account, and I’m using a template similar to the example above. Where it checks if the idclient is equal to the idclient within the item table and so can show.

  • I do not understand your doubt, you can return a list without problems in the same way that returns a record. in this case you will treat something similar to a query with a user, however your application should return a list

  • The application is ASP.NET MVC or Web API 2?

  • Web API 2. Using "Return users[i];" will return a single record, correct?

Show 2 more comments

1 answer

0


Only insert to a list and at the end of the for return the result in this way:

getUser: function(id){
    var users = [];
    for(i=0;i<users.length;i++){
        if(users[i].id == id){
            users.push(users[i]);
        }
    }
    return users;
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.