Last active
August 29, 2015 14:25
-
-
Save SergeyNarozhny/31815f5f17dc3dbb55d8 to your computer and use it in GitHub Desktop.
AngularJS example offer generator
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(function(){ | |
var app = angular.module("kp", ['angularFileUpload', 'ngRoute', 'ngAnimate', 'ngSanitize']); | |
app.config(['$routeProvider', '$locationProvider', function($routeProvider, $locationProvider){ | |
$routeProvider | |
.when("/", { | |
templateUrl: "/offer/edit-template.html", | |
controller: "KpController", | |
controllerAs: "kp", | |
resolve: { | |
'isAdmin': ['$http', '$q', function($http, $q) | |
{ | |
var deferred = $q.defer(); | |
$http.get('/offer/adm.php').then( | |
function success(response) | |
{ | |
if (response.data.err) | |
{ | |
angular.element("#last_page_error").show().append(response.data.msg); | |
deferred.reject(false); | |
} | |
else deferred.resolve(true); | |
}, | |
function error(response) { deferred.reject(false); } | |
); | |
return deferred.promise; | |
}] | |
} | |
}) | |
.when("/:token/", { | |
templateUrl: "/offer/view-template.html", | |
controller: "KpView", | |
controllerAs: "kv", | |
resolve: { | |
'token': ['$q', '$route', '$location', function ($q, $route, $location) | |
{ | |
var token = $route.current.params.token, | |
deferred = $q.defer(); | |
if (token.length === 8) | |
{ | |
deferred.resolve(token); | |
} else | |
{ | |
deferred.reject('Wrong token!'); | |
$location.path('/'); | |
} | |
return deferred.promise; // promise loads views' data after the resolve of route function | |
}] | |
} | |
}); | |
$locationProvider.html5Mode(false).hashPrefix('!'); | |
}]); | |
app.factory('SharedFn', function() { | |
var sharedFn = {}; | |
sharedFn.init = function(scope) | |
{ | |
scope.discount = 0; | |
scope.discountShowProc = scope.discountShowRub = false; | |
scope.simplePopup = null; | |
} | |
sharedFn.getTotal = function(scope, target) | |
{ | |
var total = 0; | |
for(var i = 0; i < scope.products.length; i++) | |
{ | |
total += (scope.products[i].price * scope.products[i].quantity + parseFloat(scope.products[i].printVal)); | |
} | |
target.gui.kp_total = total; | |
return total; | |
} | |
sharedFn.getDiscount = function(scope, target) | |
{ | |
var discount; | |
if (scope.discountShowProc && !scope.discountShowRub) | |
{ | |
discount = scope.getTotal() * scope.discountProc / 100; | |
} | |
else if (scope.discountShowRub && !scope.discountShowProc) | |
{ | |
discount = scope.discountRub; | |
} | |
target.gui.kp_discount = discount; | |
target.gui.discountProc = scope.discountProc; | |
return discount; | |
}; | |
return sharedFn; | |
}); | |
app.controller("KpView", ['$http', '$q', '$scope', 'token', 'SharedFn', function($http, $q, $scope, token, SharedFn) | |
{ | |
var base = this; | |
if (!!token) | |
{ | |
$http.get('/offer/hash.php?token='+token) | |
.success(function(data, status, headers, config) | |
{ | |
base.products = data.ITEMS; | |
base.flags = data.FLAGS; | |
base.gui = data.GUI; | |
angular.element("#offer_main_wrap")[0].className = base.gui.bgcolor; | |
SharedFn.init(base); | |
base.styles.product.cursor = "default"; | |
console.log(base); | |
if (base.gui.address) | |
{ | |
base.gui.address = base.gui.address.trim().replace(/\<br[\/]*\>/g, "\n"); | |
} | |
//base.getTotal = SharedFn.getTotal(base); | |
//base.getDiscount = SharedFn.getDiscount(base); | |
}); | |
} | |
}]); | |
app.controller("KpController", ['$http', '$q', 'MyFileUploader', '$location', '$scope', 'SharedFn', function($http, $q, MyFileUploader, $location, $scope, SharedFn) | |
{ | |
$scope.$on("$routeChangeError", function(){}); | |
var base = this; | |
base.prodfile = $http.get('/offer/basket.php'); | |
base.flagfile = $http.get('/offer/flist2.json'); | |
base.toksfile = $http.get('/offer/hash.php'); | |
base.userfile = $http.get('/offer/user.php'); | |
base.products = base.flags = []; | |
$q.all([base.prodfile, base.flagfile, base.toksfile, base.userfile]).then(function(values) | |
{ | |
if (values[0].data.err) | |
{ | |
$scope.$destroy(); | |
throw new Error("403 error, forbidden! " + values[0].data.msg); | |
} | |
else { base.products = values[0].data; } | |
base.flags = values[1].data; | |
$scope.tokens = values[2].data; | |
$scope.user = values[3].data; | |
//head img | |
base.kpheadimg = []; | |
if ($scope.user.LOGO && $scope.user.LOGO.SRC) base.kpheadimg.push($scope.user.LOGO.SRC); | |
else base.kpheadimg.push("/upload/tmp/zork.jpg"); | |
//head contacts | |
var defcontact = ['Нина Иванова', '[email protected]', '+7(812)000-00-00']; | |
base.headcontacts = defcontact.join('<br/>'); | |
base.loader = 1; // sort of helper, showing ajax load | |
if (base.products.length) | |
{ | |
base.getTotal = function(){ | |
return SharedFn.getTotal(base, $scope); | |
} | |
base.getDiscount = function (){ | |
return SharedFn.getDiscount(base, $scope); | |
} | |
base.productRemove = function(index){ | |
this.products.splice(index,1); | |
} | |
for (var i = 0; i < base.products.length; i++) | |
{ | |
base.products[i].uploader = new MyFileUploader({ url: 'upload.php', name: base.products[i].name, findex: function(){ | |
for (var j = 0; j < base.products.length; j++) | |
{ | |
if (base.products[j].name == this.name) return j; | |
} | |
return false; | |
}, removeAfterUpload: true, queueLimit: parseInt(4 - base.products[i].photo.length) }); | |
base.products[i].uploader.onCompleteItem = function(fileItem, response, status, headers) | |
{ | |
if (fileItem.isSuccess && response.answer) | |
{ | |
base.products[this.findex()].photo.push("/offer/uploads/" + response.filename); | |
this.queueLimit = this.queueLimit - 1; | |
} | |
} | |
} | |
} | |
if ($scope.tokens.length) | |
{ | |
base.randToken = $scope.tokens[Math.floor(Math.random() * $scope.tokens.length)]; | |
base.checkDescDataFlagValues = function(flagname) | |
{ | |
for (var i = 0; i < this.flags.length; i++) | |
{ | |
if (this.flags[i].state === false && this.flags[i].id === flagname) | |
{ | |
return true; | |
} | |
} | |
return false; | |
} | |
base.productsGetCopy = function() | |
{ | |
var newArr = []; | |
for (var i = 0; i < this.products.length; i++) | |
{ | |
newArr[i] = {}; | |
for (var y in this.products[i]) | |
{ | |
if (~["artnumber", "data", "description", "name", "photo", "price", "print", "printVal", "quantity"].indexOf(y)) | |
{ | |
if (y === "data" && this.checkDescDataFlagValues("show_data")) { continue; } | |
else if (y === "description" && this.checkDescDataFlagValues("show_des")) { continue; } | |
newArr[i][y] = this.products[i][y]; | |
} | |
} | |
} | |
return newArr; | |
} | |
base.sendTokenData = function() | |
{ | |
this.wellsmShow = true; | |
this.productsRelease = this.productsGetCopy(); | |
//this.productsRelease = angular.copy(this.products); | |
$scope.gui['head_img'] = this.kpheadimg[0]; | |
$scope.gui['bgcolor'] = this.bgcolor; | |
$http.post('/offer/hash.php', { flags: base.flags, gui: $scope.gui, token: base.randToken, items: base.productsRelease }) | |
.success(function(data, status, headers, config) | |
{ | |
base.wellsmLinkShow = true; | |
}); | |
} | |
} | |
}, function(errors) { console.log(errors, "error!"); }); | |
$scope.gui = { kp_name: 'Коммерческое предложение' }; | |
SharedFn.init(base); | |
base.bgselect = function(item) | |
{ | |
base.bgselected = item; | |
base.bgcolor = $scope.bgcolor = 'bigbg'+item; | |
} | |
base.bgisActive = function(item) { return base.bgselected === item } | |
base.bgcolor = $scope.bgcolor = "bigbg0"; | |
base.bgselect(0); | |
$scope.$watch('bgcolor', function(newBg, oldBg) | |
{ | |
angular.element("#offer_main_wrap")[0].className = newBg; | |
}); | |
var uploader = base.uploader = new MyFileUploader({ url: 'upload.php', removeAfterUpload: true, queueLimit: 2 }); | |
uploader.onCompleteItem = function(fileItem, response, status, headers) | |
{ | |
if (fileItem.isSuccess && response.answer) | |
{ | |
base.kpheadimg.push("/offer/uploads/" + response.filename); | |
this.queueLimit = this.queueLimit - 1; | |
} | |
} | |
base.absUrl = function() | |
{ | |
return $location.$$absUrl; | |
} | |
}]); | |
app.directive('contenteditable', function(){ | |
return { | |
restrict: "A", | |
link: function(scope, elm, attrs) | |
{ | |
elm.on('blur', function() | |
{ | |
if (elm.html() == "") | |
{ | |
elm.html(scope.tmpValue); | |
} | |
else | |
{ | |
if (attrs.name && attrs.name.length && attrs.name.match(/^gui_/).length) | |
{ | |
var name = attrs.name.replace("gui_", ""); | |
if (name === "kp_total" || name === "kp_discount") | |
{ | |
scope.gui[name] = elm.html().replace(",", ""); | |
} | |
else | |
{ | |
scope.gui[name] = elm.html(); | |
} | |
} | |
if (attrs.model && attrs.model.length && attrs.model.match(/^product./).length) | |
{ | |
var prop = attrs.model.replace("product.", ""); | |
if (prop === "price" || prop === "totalPrice" || prop === "printVal") | |
{ | |
scope.product[prop] = elm.text().replace(",", ""); | |
} | |
else | |
{ | |
scope.product[prop] = elm.text(); | |
} | |
} | |
scope.$apply(); | |
} | |
}).on('focus', function(){ | |
scope.tmpValue = elm.html(); | |
}); | |
} | |
}; | |
}); | |
app.directive('popupchooser', function($compile){ | |
return { | |
restrict: "A", | |
scope: | |
{ | |
modaluploader: '=', | |
kpheadimg: '=', | |
kpstyles: '=' | |
}, | |
templateUrl: 'modal-template.html', | |
link: function(scope, elm, attrs) { | |
scope.show = false; | |
scope.hideModal = function() | |
{ | |
scope.show = false; | |
}; | |
scope.toggleModal = function() | |
{ | |
scope.show = !scope.show; | |
}; | |
scope.kpheadimgChange = function(index) | |
{ | |
scope.kpheadimgtmp = scope.kpheadimg[0]; | |
scope.kpheadimg[0] = scope.kpheadimg[index]; | |
scope.kpheadimg[index] = scope.kpheadimgtmp; | |
} | |
} | |
}; | |
}); | |
app.directive('ngThumb', ['$window', function($window) { | |
var helper = { | |
support: !!($window.FileReader && $window.CanvasRenderingContext2D), | |
isFile: function(item) { | |
return angular.isObject(item) && item instanceof $window.File; | |
}, | |
isImage: function(file) { | |
var type = '|' + file.type.slice(file.type.lastIndexOf('/') + 1) + '|'; | |
return '|jpg|png|jpeg|bmp|gif|'.indexOf(type) !== -1; | |
} | |
}; | |
return { | |
restrict: 'A', | |
template: '<span class="glyphicon glyphicon-remove-circle inserted_before" ng-click="item.remove()" ng-disabled="!modaluploader.queue.length" ng-show="modaluploader.queue.length"></span><canvas/>', | |
link: function(scope, element, attributes) { | |
if (!helper.support) return; | |
var params = scope.$eval(attributes.ngThumb); | |
if (!helper.isFile(params.file)) return; | |
if (!helper.isImage(params.file)) return; | |
var canvas = element.find('canvas'); | |
var reader = new FileReader(); | |
reader.onload = onLoadFile; | |
reader.readAsDataURL(params.file); | |
function onLoadFile(event) | |
{ | |
var img = new Image(); | |
img.onload = onLoadImage; | |
img.src = event.target.result; | |
} | |
function onLoadImage() | |
{ | |
var width = params.width || this.width / this.height * params.height; | |
var height = params.height || this.height / this.width * params.width; | |
canvas.attr({ width: width, height: height }); | |
canvas[0].getContext('2d').drawImage(this, 0, 0, width, height); | |
} | |
} | |
}; | |
}]); | |
app.factory('MyFileUploader', ['FileUploader', function(FileUploader) | |
{ | |
FileUploader.inherit(MyFileUploader, FileUploader); | |
function MyFileUploader(options) | |
{ | |
MyFileUploader.super_.apply(this, arguments); | |
this.filters.unshift({ name: 'imageFilter', fn: this._imageFilter }); | |
} | |
MyFileUploader.prototype._imageFilter = function(item, options) | |
{ | |
var type = '|' + item.type.slice(item.type.lastIndexOf('/') + 1) + '|'; | |
return '|jpg|png|jpeg|bmp|gif|'.indexOf(type) !== -1; | |
} | |
return MyFileUploader; | |
}]); | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment