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;};
});
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.