pass variable of the view to the angular factory js

0

Friends, I want to send this id that prints a ng-repeat

<p>{{ p.id }} </p>  

to a factory to concatenate it in a url

    http://api/products/"+paramId+"?token="
             +localStorage.getItem('token')+"&user_id="+localStorage.getItem('user_id');

.factory('ProductosId',function($q, $http, $location){

   var Api = {};

    $http.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';

    Api.productosId = function() {

        var defer = $q.defer();

        var paramId = $location.search().idp; 

        var urlaux = "http://api/products/"+paramId+"?token="
         +localStorage.getItem('token')+"&user_id="+localStorage.getItem('user_id');

        $http({
            method: 'GET',
            url: urlaux,
        }).success(function(data) {
            defer.resolve(data);
        })
        return defer.promise;
    }
    return Api;
})

already there is done, sending it by parameters and capturing it in the factory but I want to do a method that prevents me from sending it by parameter because I will not use another view if not a modal.

    
asked by frd 02.09.2016 в 01:19
source

1 answer

1

Pass it by parameters to the function in this way

vista -> controller -> Factory

For this you only have to modify the Factory in this way

Api.productosId = function(paramId) {

    var urlaux = "http://api/products/"+paramId+"?token="
         +localStorage.getItem('token')+"&user_id="+localStorage.getItem('user_id');

    return $http({
            method: 'GET',
            url: urlaux,
    });
}

By the way you will have noticed that I have eliminated the deferred. You are incurring what is known as the explicit construction antipattern or explicit construction antipattern . You do not have to create a deferred in your code, the $http method already gives you a promise so you return that same.

In your controller you declare something like this

$scope.getById = function(paramId) {
    Api.productosId(paramId).then(function(response) {
        // Manipulas los resultados
    }).catch(function(err) {
        // Manejas el error
    });
};

and your view, within ng-repeat you put a button or something similar and use the ng-click directive. This is an example

<div ng-repeat="p in products">
    <p>{{ p.id }} </p> 
    <button type="button" ng-click="getById(p.id)">Enviar</button>
</div>
    
answered by 02.09.2016 в 14:16