在AngularJS中全局生成一个工厂JS变量 [英] Make a factory JS variable available globally in AngularJS

查看:87
本文介绍了在AngularJS中全局生成一个工厂JS变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



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

我希望使用新的计算值为

结果。

on

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

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



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



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

  // Ionic Starter App 

// angular.module是创建,注册和检索Angular模块的全局地方
//'starter'是此角度模块示例的名称(也设置在< body>属性中在index.html)
//第二个参数是一个'require'数组
angular.module('starter',['ionic','ngCordova'])
$ b $ (函数($ ionicPlatform){
$ ionicPlatform.ready(函数(){



if(window.cordova&& window。 cordova.plugins.Keyboard){
//默认情况下隐藏配件栏(将其删除以显示键盘上方的配件栏
//用于表单输入)
cordova.plugins.Keyboard。 hideKeyboardAccessoryBar(true);

//不要删除th是线路,除非你知道你在做什么。当文本输入焦点时,它停止视口
//捕捉。 Ionic在内部处理
//更好的键盘体验。
cordova.plugins.Keyboard.disableScroll(true);
}
if(window.StatusBar){
StatusBar.styleDefault();
}
});


.config(函数($ 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'
}
}
})

//如果以上状态都不匹配,则使用此作为后备
$ urlRouterProvider.otherwise('/ tab / home');
$ b $)
$ b $ .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;
}
};
返回httpInterceptor;
})
.config(函数($ httpProvider){
$ httpProvider.interceptors.push('httpInterceptor');
})

。控制器('ListController',''$ scope','$ http','$ state','$ stateParams','$ window','$ location','$ ionicPopup',函数($ scope,$ http, $ state,$ stateParams,$ cordovaBluetoothSerial,$ window,$ location,$ ionicPopup){

$ scope.query ='';

$ scope.getOrders = function(查询){

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

})
}

//$scope.orders = [];

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

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

发票['itemList'] = myItems;
发票['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 =现金,卡,贝宝;
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);
}

}]);


解决方案

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

$ $ p $ .factory(' httpInterceptor',函数($ 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 + re sults [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; //将修改后的项目放回响应中
deferred.resolve(response);
return deferred.promise;
}
};
返回httpInterceptor;
})


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

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

I wish to use the new calculated value for

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

on

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 done before my http interceptor code that calculates the new amount. myItem['unitPrice'] = order.data.bkor_payamount;

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

I have tried making a new variable that i read would create a global variable but this doesn't seem to have worked within the app. At the moment it still calls the original value gathered from the JSON url rather than my calculation.

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

        }]);

解决方案

A little busy now, but I think you may want to put back the results in the data field of your resolve object in your httpInterceptor factory. And I changed the references to result in your forEach() to results[key] to be sure it modifies the original array (Hope 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;
    })

这篇关于在AngularJS中全局生成一个工厂JS变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆