javascript - Mapping a list of items in an array to a function parameter -


i have angular controller , service.

the controllers calls service, , passes data , endpoint.

my service performs http request, trying refactor code pass in endpoint controller, , service tries match endpoint list of array.

controller:

app.controller('mycontroller', function($scope, myservice) {      $scope.buttonclick = function(endpoint) {         myservice.postaction(endpoint, $scope.postdata)             .success(function (data, status, headers, config) {                  console.log("success");                                 })              .error(function (data, status, headers, config) {                 console.log("error");                                  });     } 

myservice:

app.factory('myservice', function ($http) {      var endpoints = [         'cart/cartdetails',         'customer/addressinfo',         'payment/shippinginfo',     ]      return {         postaction: function(endpoint, postdata) {             return $http({                 method: 'post',                 url: endpoint,                 data: postdata,                 headers: {'content-type': 'application/json'}             });         }     }; }); 

depending on button clicked via $scope.buttonclick, of endpoints passed, e.g.

<button ng-click="buttonclick('shippinginfo')>shipping</button> <button ng-click="buttonclick('addressinfo')>address</button> <button ng-click="buttonclick('certdetails')>cart</button> 

your endpoints should object

app.factory('myservice', function ($http) {      var endpoints = {'certdetails': 'cart/cartdetails','addressinfo': 'customer/addressinfo','shippinginfo': 'payment/shippinginfo'}       return {         postaction: function(endpoint, postdata) {             return $http({                 method: 'post',                 url: endpoints[endpoint],                 data: postdata,                 headers: {'content-type': 'application/json'}             });         }     }; }); 

Comments

Popular posts from this blog

php - Wordpress website dashboard page or post editor content is not showing but front end data is showing properly -

javascript - Get parameter of GET request -

javascript - Twitter Bootstrap - how to add some more margin between tooltip popup and element -