0

If 'User' is a service and 'User.get' is a method that doing a request.

<button class="btn" ng-click="User.get(users,'id,uname,email,pw')">
<p>{{users}}</p>

How do I assign the request data to the scope variable 'users' with that code example? I like that code style but I do not know how to implement it. Any ideas?

example on the service provider:

angular.module('User',[]).
provider('User', function() {
    var path = 'user.php';
    this.$get = function($http) {
        var r = {};
        r.get = function(variable,fields){
            $http.get(path+'?fields='+fields).
            success(function(data){
                //variable = data;
            });
        }
        return r;
    };
    this.setPath = function(p){path = p;};
});
Jossi
  • 1,020
  • 1
  • 17
  • 28

1 Answers1

4

Use a controller and write the handler for the ng-click inside it. Here's an example:

Controller:

function Ctrl($scope) { 
    $scope.getUsers = function (fields) {
        $scope.users = User.get(fields);
    }
}

HTML:

<div ng-controller="Ctrl">
    <button class="btn" ng-click="getUsers('id,uname,email,pw')">
    <p>{{users}}</p>
</div>

Another way to do it is to pass the this reference (scope) and the property name ('users') into the service:

<button class="btn" ng-click="User.get(this, 'users', 'id,uname,email,pw')">

And then on the User service, after getting the result, do something like this:

r.get = function(scope, prop, fields){
        $http.get(path+'?fields='+fields).
        success(function(data){
            scope[prop] = data;
        });
}

where scope = this and prop = 'users'.

IMHO, the first approach is the best one, the second one sounds a little hacky.

bmleite
  • 26,850
  • 4
  • 71
  • 46
  • I did some improvement on your example and its posseble to just call User.get('users','id,uname,email,pw') without 'this'. But instead set the 'User.scope = $scope;' in the controller and 'r.scope[prop] = data;' in the callback function, then I dont have to worry about adding a argument for 'this' all the time :) – Jossi Feb 07 '13 at 02:06
  • @Jossi be careful with those asynchronous requests, if you change the `User.scope` while an API request is being processed on the server you will end up adding the result to the wrong scope. This means that using `User.get()` in more than 1 place can be problematic. – bmleite Feb 07 '13 at 10:39