angularjs写公共方法
'use strict'; angular.module('fast-westone') .factory('commonUtilService', function () { return { /** * 将json转成form Data * @param params * @returns {string} */ transform: function (params) { var str = []; for (var p in params) { var a = params[p] ; if(!a && a!= false && a != 0 ) continue ; if (typeof params[p] === 'object') { str.push(encodeURIComponent(p) + '=' + encodeURIComponent(angular.toJson(params[p]))); } else { str.push(encodeURIComponent(p) + '=' + encodeURIComponent(params[p])); } } return str.join('&'); } } })
调用的地方:
"use strict"; angular.module("fast-westone").controller('blServerUpdateCtrl', function ($scope, blServerServiceOperation, toastr, $uibModal, $log, commonUtilService) { $scope.editServer.desc = $scope.getDesc($scope.orinalServer); var transform = function (params) { var str = []; for (var p in params) { var a = params[p] ; if(!a && a!= false && a != 0 ) continue ; if (typeof params[p] === 'object') { str.push(encodeURIComponent(p) + '=' + encodeURIComponent(angular.toJson(params[p]))); } else { str.push(encodeURIComponent(p) + '=' + encodeURIComponent(params[p])); } } return str.join('&'); }; /** * 保存 */ $scope.ok = function () { var paramObj = { name: $scope.editServer.name, desc: $scope.editServer.desc }; paramObj = commonUtilService.transform(paramObj); blServerServiceOperation.operate($scope.editServer.id, paramObj, 'update').$promise.then(function (resp) { toastr.success('修改虚拟机成功'); $scope.modal.dismiss('cancel'); },function(error){ $log.error(error); toastr.success('修改虚拟机失败'); }); }; /** * 取消 */ $scope.cancel = function () { $scope.modal.dismiss('cancel'); }; });