在AngularJS中为全局提供工厂JS变量

时间:2016-08-24 14:51:05

标签: javascript angularjs global-variables

我在工厂内创建了一个变量,我希望在AngularJS的控制器中的另一个函数中使用。

如何从我的ListController onPay函数可用的工厂创建变量?

我希望使用

的新计算值

result.data.bkor_payamount = result.data.bkor_payamount.toFixed(2); (来自工厂)

myItem [' unitPrice'] = result.data.bkor_payamount; (ListController中的onPay函数)

例如,我可以使用下面的代码,它将传递在计算新数量的http拦截器代码之前完成的原始值。 myItem [' unitPrice'] = order.data.bkor_payamount;

只需要从result.data.bkor_payamount创建新值;可以在我的List_Controller中使用

我试过制作一个我读过的新变量会创建一个全局变量,但这似乎并没有在应用程序中起作用。目前它仍然调用从JSON url收集的原始值而不是我的计算。

// 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");
                }

        }]);

2 个答案:

答案 0 :(得分:0)

角度服务是单身人士。因此,您可以将结果存储在服务实例的属性中,并将其注入到控制器需要数据的位置

如果您需要这些结果以便在刷新后继续存在,那么您将需要使用本地存储

此外,根本不推荐,但您可以将其存储在全局窗口对象中。

答案 1 :(得分:0)

现在有点忙,但我想您可能希望将结果放回httpInterceptor工厂中解析对象的数据字段中。我将resultforEach()的引用更改为results[key],以确保修改原始数组(希望这是一个数组?)

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