MikeDiam
MikeDiam

Reputation: 111

Angular resource .get does not change the passed value of user ID after ng-init

I use ng-init in the template to pass the curUID to the controller. Afterwards, controller should get information in the service, using curUID as an URL parameter.

Controller:

        $scope.getCurUID = function() {
        return parseInt($scope.curUID, 10);
    }
    $scope.curUser = hosterFactory.getHoster().get({id:$scope.getCurUID(), isArray:true}).$promise.then(
            function(response){
                respose = $scope.changeData(response);
                $scope.curUser = response; 
                console.log("curUser: (curUID): "+parseInt($scope.curUID, 10));
                console.log(response);
            },
            function(response) {
                console.log("error curUser: ");
                console.log(response);
                $scope.message = "Error: "+response.status + " " + response.statusText;
            }
    );

Service:

    .service('hosterFactory', ['$resource', 'baseURL', function($resource,baseURL) {

        this.getHoster = function(){
            var res = $resource("/api/rest/user/:id", null,  {'get':{method:'GET', isArray:true},'update':{method:'PUT' }});
            return res;
        };

    }])

If I directly write in .get id as 207 (for example) all works fine. But if I use the approach above - .get use curUID as 0 - it is wrong.

Upvotes: 0

Views: 45

Answers (1)

JB Nizet
JB Nizet

Reputation: 691943

Here's what happens, in chronological order:

  • the controller is instanciated
  • the controller function is thus executed and calls hosterFactory.getHoster().get({id:$scope.getCurUID() ...
  • ng-init sets the current user ID

You shouldn't use ng-init. It's explicitly documented as something you should (almost) never use. There is a better way. It's hard to tell what, since I don't know what the controller is used for, and what your application looks like.

If you want to do still use ng-init, then it should look like this:

ng-init="init(theUserId)"

and the $scope.init() function should take the passed userId, and make the HTTP request.

Upvotes: 1

Related Questions