标签:style blog http color io ar for div cti
angularjs 其实也有一个currency指令,不过好像只是换符号而已。
这里自己写了一个简单的兑换率filter
<div ng-controller="ctrl"> <div>{{ 100 | myCurrency}}</div> <div ng-click="change1(‘SGD‘)">change</div> </div> angular.module("Main", dependentModuleList). controller("ctrl", function ($scope, currencyService) { $scope.change1 = function (code) { currencyService.changeCodeTo(code); }; });
调用大概是这样的 , 100 应该变成 USD 100.00 ,点击事件后就兑换成 SGD xx.xx
angular.module("Currency", []). provider("currencyService", [function () { var that = this; this.defaultCode = "USD"; //允许通过provider修改 this.$get = ["$rootScope", function ($rootScope) { var COOKIE_KEY = "currecyCode"; var SERVICE_PATH = "//service.stooges.com.my/currency.ashx?defaultCode=" + that.defaultCode; //这里可以请求一个当前的 rate table (来自 http://www.xe.com/currencytables) var defaultCode = that.defaultCode; var currentCode = G.s.Cookie.get(COOKIE_KEY) || defaultCode; var rateColletion = {}; //{USD:3.1538542348} var ajaxing = false; function getRateFromServer() { ajaxing = true; G.s.fn.jsonp(SERVICE_PATH).then(function (response) { ajaxing = false; rateColletion = JSON.parse(response).data; $rootScope.$digest(); //手动渲染 }, function () { console.log("get currency rate table fail !"); }); } function getMoneyFormat(money, code) { return code + " " + (parseFloat(money).toFixed(2)); } return { changeCodeTo: function (code) { currentCode = code; //请在外部digest G.s.Cookie.set(COOKIE_KEY, currentCode, new Date().addMonths(1)); }, convertMoney: function (money) { if (defaultCode === currentCode || ajaxing) { //正在向服务器请求的话也直接返回 return getMoneyFormat(money, currentCode); } var rate = rateColletion[currentCode]; if (rate != undefined) { return getMoneyFormat(money / rate, currentCode); //这里是用除法 } else { getRateFromServer(); //第一次得向服务器请求rate表格 return getMoneyFormat(money, currentCode); } } } }] }]). filter("myCurrency", ["$rootScope", "currencyService", function ($rootScope, currencyService) { //手动调用的话要注意, 如果没有rate,会直接返回原value return function (money) { return currencyService.convertMoney(money); } }]);
过程是通过渲染时判断当前货币然后去服务端获取兑换率表格进行兑换。这里用的是一个jsonp请求。
需要判断只请求一次,请求返回时得手动渲染。
标签:style blog http color io ar for div cti
原文地址:http://www.cnblogs.com/keatkeat/p/3950597.html