Search code examples
angularjsangularjs-serviceangularjs-controllerangularjs-http

How to pass $http data from Service to Controller in AngularJS


AngularJS not working when I pass controller to the view

I have a problem and I can't troubleshoot it. In my simple app (very simple) I have a service that provides of users info. In angular I have an mvc which is trying to bind the info into the view.

The problem: when I pass the controller to the view, in the route directive, angular stops working in the view. I'm using a simple test {{1+1}} to verify if angular is working.

controller:

App.controller("loginController", function ($scope, usersModel) {

    $scope.users = usersModel.getUsers();

})

model

App.service("usersModel", function () {

    this.getUsers = function ($scope) {
        $http.get("http://localhost:50765/api/users");
    }});

Solution

  • The service should inject the $http service and return the promise that it returns

    App.service("usersModel", function ($http) {
    
        this.getUsers = function () {
            return $http.get("http://localhost:50765/api/users");
        }
    });
    

    And extract the data from the promise:

    App.controller("loginController", function ($scope, usersModel) {
    
        var promise = usersModel.getUsers();
        promise.then(function(response) {
            $scope.users = response.data;
        });
    
    })