Search code examples
javascriptangularjsangular-promiseangularjs-httpng-init

AngularJS ng-init does not work


When i go to list.html right after loading the page it doesnt show me the list. I need to go to form.html first and then back to list.html and then it gives me the list. When i had $http functions in controller it worked as i wanted but now that they are in service they dont work like before.

app.js

app.service("dataservice", function($http){

    var list = [{}];

    this.get = function(){
        $http.get("harjoitus22/backend.php").success(function(response){
            list = response;
        });
    };

    this.save = function(newcontact){

        $http({
            method: 'post',
            url: 'harjoitus22/backend.php',
            data: newcontact,
            header: 'Access-Control-Allow-Origin: *'
        }).success(function(response){
            list = response;            
        });         
    }; 

    this.give = function(){
        return list;
    };
});

app.controller("mainController", function($scope, $location, dataservice){

    $scope.save = function(){    
        dataservice.save($scope.newcontact);
        $scope.newcontact = {};
        $location.path("/list");
        $scope.list = dataservice.give();
    };

    $scope.get = function(){
        dataservice.get();
        $scope.list = dataservice.give();
    };
});

list.html

    <tbody ng-init="get()">
        <tr ng-repeat="object in list">
            <td>{{object.nimi}}</td>
            <td>{{object.email}}</td>
            <td>{{object.ruoka}}</td>
            <td>{{object.sauna}}</td>
        </tr>
    </tbody>

Solution

  • $http call works asynchronously, when you call it, It will not give you response on next line execution. To keep eye on that ajax you should take use of promise return by $http method.

    For achieving the same you need to return promise object from the service get method ($http methods does return's promise object, which helps you to execute your code by putting up in its .then function's).

    Service

    this.get = function(){
        return $http.get("harjoitus22/backend.php").then(function(res){
            list = res.data;
        });
    };
    

    Controller

    dataservice.get().then(function(){
       $scope.list = dataservice.give();
    });