Make JS factory variable globally accessible in AngularJS

I have a variable created inside a factory that I want to use in another function in my controllers in AngularJS.

How can I make a variable from factory available to my ListPontroller onPay function?

I want to use the new calculated value for

result.data.bkor_payamount = result.data.bkor_payamount.toFixed (2); (from factory)

about

myItem ['unitPrice'] = result.data.bkor_payamount; (onPay function in ListController)

For example, I can use this code below, and it will pass the original value executed before my http interceptor, which calculates the new amount. myItem ['unitPrice'] = order.data.bkor_payamount;

Just need to make a new value from result.data.bkor_payamount; available for use in my List_Controller

I tried to make a new variable that I read, create a global variable, but this does not seem to work in the application. At the moment, it still calls the original value retrieved from the JSON URL, not my calculations.

// Ionic Starter App

        // angular.module is a global place for creating, registering and retrieving Angular modules
        // 'starter' is the name of this angular module example (also set in a <body> attribute in index.html)
        // the 2nd parameter is an array of 'requires'
        angular.module('starter', ['ionic','ngCordova'])

        .run(function($ionicPlatform) {
          $ionicPlatform.ready(function() {



            if(window.cordova && window.cordova.plugins.Keyboard) {
              // Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
              // for form inputs)
              cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);

              // Don't remove this line unless you know what you are doing. It stops the viewport
              // from snapping when text inputs are focused. Ionic handles this internally for
              // a much nicer keyboard experience.
              cordova.plugins.Keyboard.disableScroll(true);
            }
            if(window.StatusBar) {
              StatusBar.styleDefault();
            }
          });
        })

        .config(function($stateProvider, $urlRouterProvider) {

          $stateProvider
            .state('tabs', {
              url: '/tab',
              cache: false,
              abstract: true,
              templateUrl: 'templates/tabs.html'
            })
            .state('tabs.home', {
              url: '/home',
              cache: false,
              views: {
                'home-tab' : {
                 templateUrl: 'templates/home.html'
                }
              }
            })
            .state('tabs.list', {
              url: '/list',
              cache: false,
              views: {
                'list-tab' : {
                 templateUrl: 'templates/list.html',
                 controller: 'ListController'
                }
              }
            })

              // if none of the above states are matched, use this as the fallback
              $urlRouterProvider.otherwise('/tab/home');

        })

        .factory('httpInterceptor', function($q, $rootScope, $window) {
            var httpInterceptor = {
                response: function(response) {
                    var deferred = $q.defer();
                    var results = response.data;
                    var urlStart = 'http://example.com/';
                    if (response.config.url.startsWith(urlStart)) {
                        angular.forEach(results, function(result, key) { 
                            result.data.estCardFee = 2.00;
                            result.data.bkor_bookingfee = result.data.estCardFee;
                            result.data.bkor_payamount = +result.data.bkor_subtotal + +result.data.bkor_handling + -result.data.bkor_discount + +result.data.bkor_adjustment + +result.data.bkor_bookingfee;
                            result.data.bkor_payamount = result.data.bkor_payamount.toFixed(2);
                            result.data.bkor_paypalamount = result.data.bkor_payamount;
                        });
                    }
                    deferred.resolve(response);
                    return deferred.promise;
                }
            };
            return httpInterceptor;
        })
        .config(function($httpProvider) { 
            $httpProvider.interceptors.push('httpInterceptor'); 
        })

        .controller('ListController', ['$scope', '$http', '$state','$stateParams', '$window', '$location', '$ionicPopup', function($scope, $http, $state, $stateParams, $cordovaBluetoothSerial, $window, $location, $ionicPopup) {

                  $scope.query = '';

                  $scope.getOrders= function(query){

                         $http.get('http://example.com/' + query).success(function(data) {
                          $scope.orders = data;
                          console.log($scope.query);
                          console.log(data);
                          console.log($scope.orders);

                         })
                  }

                //$scope.orders = [];

                 function onPay(order) {
                 var itemsArr = [];
                 var invoice = {};
                 var myItems = {};
                 var myItem = {};

                 myItem['unitPrice'] = result.data.bkor_paypalamount;
                 myItem['taxRate'] = '0.0';
                 myItem['taxName'] = 'Tax';
                 itemsArr.push(myItem);
                 myItems['item'] = itemsArr;

                 invoice['itemList'] = myItems;
                 invoice['paymentTerms'] = 'DueOnReceipt';
                 invoice['currencyCode'] = 'GBP';
                 invoice['discountPercent'] = '0';

                 var returnUrl = "http://example.com/";
                 var retUrl = encodeURIComponent(returnUrl + "?{result}?Type={Type}&InvoiceId={InvoiceId}&Tip={Tip}&Email={Email}&TxId={TxId}");
                 var pphereUrl = "paypalhere://takePayment/v2?returnUrl=" + retUrl;
                 pphereUrl = pphereUrl + "&accepted=cash,card,paypal";
                 pphereUrl = pphereUrl + "&step=choosePayment";
                 pphereUrl = pphereUrl + '&invoice=' + escape(JSON.stringify(invoice));
                 console.log(pphereUrl);

                 return pphereUrl;

                 }


                $scope.pay = function (order) {
                $scope.showButton = true;
                var url = onPay(order);
                window.open(url, "_system");
                }

        }]);
+1
source share
2 answers

Now a little busy, but I think you can return the results in the data field of your permission object to the httpInterceptorfactory. And I changed the links resultin yours forEach()to results[key]to make sure that it changes the original array (hopefully this is an array?)

       .factory('httpInterceptor', function($q, $rootScope, $window) {
        var httpInterceptor = {
            response: function(response) {
                var deferred = $q.defer();
                var results = response.data;
                var urlStart = 'http://example.com/';
                if (response.config.url.startsWith(urlStart)) {
                    angular.forEach(results, function(result, key) { 
                        results[key].data.estCardFee = 2.00;
                        results[key].data.bkor_bookingfee = results[key].data.estCardFee;
                        results[key].data.bkor_payamount = results[key].data.bkor_subtotal + results[key].data.bkor_handling - results[key].data.bkor_discount + results[key].data.bkor_adjustment + results[key].data.bkor_bookingfee;
                        results[key].data.bkor_payamount = parseFloat(results[key].data.bkor_payamount).toFixed(2);
                        results[key].data.bkor_paypalamount = results[key].data.bkor_payamount;
                    });
                }
                response.data = results;  //put the modified items back in the response
                deferred.resolve(response);
                return deferred.promise;
            }
        };
        return httpInterceptor;
    })
0
source
Services

Angular . , , -

, ,

, , .

0

Source: https://habr.com/ru/post/1652331/


All Articles