I am using angular route for my project. My project structure like below.
index page
<body ng-app="myApp">
<div ng-view></div>
<script src="resources/js/angular.js" type="text/javascript"></script>
<script src="resources/angular/angular-route.js" type="text/javascript"></script>
<script src="resources/js/route.js" type="text/javascript"></script>
<script src="resources/js/quotation.js" type="text/javascript"></script>
<script src="resources/js/container_details.js" type="text/javascript"></script>
<script src="resources/angular/angular-modal-service.js" type="text/javascript"></script>
<script src="/containers/resources/js/user-registration.js" type="text/javascript"></script>
</body>
my route.js file
var app = angular.module('myApp',['ngTable','jcs-autoValidate','ngRoute']);
// configure our routes
app.config(function($routeProvider,$locationProvider) {
$routeProvider
.when('/containers', {
templateUrl : 'template.jsp'
})
.when('/container-details', {
templateUrl : 'container-details.jsp',
controller : 'myCtrl'
})
.when('/quotation-approve', {
templateUrl : 'quotation_approve.jsp',
controller : 'ourCtrl'
})
.when('/user-registration', {
templateUrl : 'user-registration.jsp',
controller : 'userCtrl'
})
$locationProvider.html5Mode(true);
});
/* app.config(["$routeProvider", "$locationProvider", function ($routeProvider, $locationProvider) {
$locationProvider.html5Mode(true);*/
I defined all modules as below:
var app = angular.module("myApp");
when i load page error occur. error said
user registration.js
var app = angular.module("myApp");
app.run(function(defaultErrorMessageResolver, validator) {
validator.setValidElementStyling(false);
defaultErrorMessageResolver.getErrorMessages().then(function(errorMessages) {
errorMessages['min-length'] = 'Username must be at least {0} letters';
errorMessages['max-length'] = 'Username must be {0} letters Only';
errorMessages['pwError'] = "Password should be atleast 8 characters long and should contain one number,one character and one special character";
errorMessages['passwordVerify'] = "password not matched";
errorMessages['validEmail'] = "Please enter a valid email address";
});
});
app.controller('userCtrl', function($scope, $http, NgTableParams, $timeout, $filter) {
$scope.getAllUserDetails = function() {
$http({
method: "GET",
url: "/containers/getUserRolle"
}).then(function mySucces(response) {
$scope.getAllRolesDetails();
$scope.userRolless = response.data.userRolles;
// console.log( $scope.userRolless);
$scope.getDatas();
}, function myError(response) {
$scope.userRolless = response.data.userRolles;
});
}
$scope.getAllTableData = function() {
// $scope.edituserdetails={};
//$scope.edituserdetails.activeuser=true;
$http({
method: "GET",
url: "/containers/getUserRolle"
}).then(function mySucces(response) {
// $scope.getAllRolesDetails();
$scope.userRolless = response.data.userRolles;
// console.log( $scope.userRolless);
$scope.getDatas();
}, function myError(response) {
$scope.userRolless = response.data.userRolles;
});
}
$scope.getDatas = function() {
console.log("tesssst" + $scope.userRolless);
//console.log("tesssst"+$scope.userRolless.object.name);
$scope.tableParams = new NgTableParams({
page: 1, // show first page
count: 5,
// count per page
// filter: {name: '' },
// sorting: { username: "asc" },
}, {
dataset: $scope.userRolless
});
}
$scope.getAllRolesDetailsById = function(roleId) {
$http({
method: "GET",
url: "/containers/getUserRoleById",
params: {
roleId: roleId
}
}).then(function mySucces(response) {
console.log(response.data.userAllRollesById);
$scope.userAllRolles = response.data.userAllRollesById;
$scope.edituserdetails.role = $scope.userAllRolles[0];
// console.log("user Active status"+ $scope.edituserdetails.activeuser);
}, function myError(response) {
console.log(response.data.userAllRolles);
$scope.userAllRolles = response.data.userAllRollesById;
});
}
$scope.editUserFunction = function(usersid) {
$http({
method: "GET",
url: "/containers/getUserDetails",
params: {
userId: usersid
}
}).then(function mySucces(response) {
$scope.edituserdetails = response.data.userDetails;
$scope.username = response.data.userDetails.username;
$scope.getAllRolesDetailsById($scope.edituserdetails.roleId);
console.log(response.data.userDetails);
console.log("user Active status" + response.data.userDetails.userstatus);
if (response.data.userDetails.userstatus === 'Y') {
$scope.edituserdetails.activeuser = true;
} else {
$scope.edituserdetails.activeuser = false;
}
$scope.edituserdetails.password = "";
$scope.edituserdetails.confirmpassword = "";
}, function myError(response) {
$scope.edituserdetails = response.data.userRolles;
});
// console.log(usersid);
}
$scope.getExistingUserValidateFunction = function(userName) {
$http({
method: "GET",
url: "/containers/validateUser",
params: {
userName: userName
}
}).then(function mySucces(response) {
var test = response.data.ExistingUserStatus
console.log("ddddd" + test);
return test;
}, function myError(response) {
// return response.data.ExistingUserStatus;
});
}
$scope.changePassword = function() {
console.log("ddddd" + $scope.edituserdetails.activeuser);
if ($scope.edituserdetails.activeuser) {
activeuserstatus = 'Y';
} else {
activeuserstatus = 'N';
}
console.log("ccccc" + activeuserstatus);
$http({
method: "POST",
url: "/containers/registrationuser",
data: {
"email": $scope.edituserdetails.email,
"username": $scope.username,
"password": $scope.edituserdetails.password,
"id": $scope.edituserdetails.id,
"role": $scope.edituserdetails.role,
"userstatus": activeuserstatus
}
})
.success(function(data) {
$timeout(function() {
$scope.msgType = false;
}, 3000);
$scope.theform.$setPristine();
if (data.errorList.length > 0) {
$scope.fieldErrorList = data.errorList;
$scope.msgType = 'Error';
} else {
$scope.msgType = 'Success';
$scope.getAllTableData();
}
$scope.theform.$setPristine();
// document.body.scrollTop = document.documentElement.scrollTop = 0;
// $scope.resetFunction();
});
// Posting data to php file
}
/* form.$setPristine = function() {
$animate.setClass(element, PRISTINE_CLASS, DIRTY_CLASS + ' ' + SUBMITTED_CLASS);
form.$dirty = false;
form.$pristine = true;
form.$submitted = false;
forEach(controls, function(control) {
control.$setPristine();
});
};*/
$scope.saveUserFunction = function() {
console.log("ddddd" + $scope.edituserdetails.activeuser);
if ($scope.edituserdetails.activeuser) {
activeuserstatus = 'Y';
} else {
activeuserstatus = 'N';
}
console.log("ccccc" + activeuserstatus);
$http({
method: "POST",
url: "/containers/registrationuser",
data: {
"email": $scope.edituserdetails.email,
"username": $scope.username,
"password": $scope.edituserdetails.password,
"id": $scope.edituserdetails.id,
"role": $scope.edituserdetails.role,
"userstatus": activeuserstatus
}
})
.success(function(data) {
console.log($scope.theform);
if (data.errorList.length > 0) {
$scope.fieldErrorList = data.errorList;
$scope.msgType = 'Error';
$scope.theform.$setPristine();
} else {
$scope.msgType = 'Success';
// $scope.edituserdetails = {};
$scope.resetFunction();
$scope.getAllTableData();
$timeout(function() {
$scope.msgType = false;
}, 3000);
$scope.theform.$setPristine();
}
// document.body.scrollTop = document.documentElement.scrollTop = 0;
$scope.resetFunction();
$scope.theform.$setPristine();
});
// Posting data to php file
}
$scope.resetFunction = function() {
$scope.edituserdetails = {};
$scope.username = '';
$scope.edituserdetails.role = $scope.userAllRolles[0];
$scope.theform.$setPristine();
}
$scope.checkPwd = function() {
var str = document.getElementById('pw').value;
if (str.length < 6) {
alert("too_short");
return ("too_short");
} else if (str.length > 50) {
alert("too_long");
return ("too_long");
} else if (str.search(/\d/) == -1) {
alert("no_num");
return ("no_num");
} else if (str.search(/[a-zA-Z]/) == -1) {
alert("no_letter");
return ("no_letter");
} else if (str.search(/^(?=.*[A-Za-z])(?=.*\d)(?=.*[$#$!%*#?&])[A-Za-z\d$#$!%*#?&]{8,}$/) != -1) {
alert("bad_char");
return ("bad_char");
}
alert("oukey!!");
return ("ok");
}
$scope.changePasswordFucntion = function(username) {
console.log(username);
$http({
method: "POST",
url: "/containers/changePassword",
data: {
"password": $scope.edituserdetails.password,
"username": username,
"curruntPassword": $scope.edituserdetails.curruntpassword,
"passwordConfirm": $scope.edituserdetails.confirmpassword
}
})
.success(function(data) {
$timeout(function() {
$scope.msgType = false;
}, 3000);
$scope.theform.$setPristine();
if (data.errorList.length > 0) {
$scope.fieldErrorList = data.errorList;
$scope.msgType = 'Error';
} else {
$scope.msgType = 'Success';
$scope.getAllTableData();
}
$scope.theform.$setPristine();
});
}
$scope.getAllRolesDetails = function() {
$http({
method: "GET",
url: "/containers/getUserAlRolles"
}).then(function mySucces(response) {
// console.log(response.data.userAllRolles);
$scope.userAllRolles = response.data.userAllRolles;
$scope.edituserdetails = response.data.userAllRolles;
$scope.edituserdetails.role = response.data.userAllRolles[0];
}, function myError(response) {
// console.log(response.data.userAllRolles);
$scope.userAllRolles = response.data.userAllRolles;
});
}
})
app.directive("passwordVerify", function() {
return {
require: "ngModel",
scope: {
passwordVerify: '='
},
link: function(scope, element, attrs, myCtrl) {
scope.$watch(function() {
var combined;
if (scope.passwordVerify || myCtrl.$viewValue) {
combined = scope.passwordVerify + '_' + myCtrl.$viewValue;
}
return combined;
}, function(value) {
if (value) {
myCtrl.$parsers.unshift(function(viewValue) {
var origin = scope.passwordVerify;
if (origin !== viewValue) {
myCtrl.$setValidity("passwordVerify", false);
return undefined;
} else {
myCtrl.$setValidity("passwordVerify", true);
return viewValue;
}
});
}
});
}
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
var app = angular.module("myApp");
This above code does not create module called myApp it just referring an existing module. If you have not yet created the module, then the error will threw which is you have mentioned.
To create the module do this.
angular.module('myApp', []);
Please read this below discussion to more details:
Meaning of the empty array in angularJS module declaration
Related
I have a controller that passes execution to a factory -- controller.getCustomerById -> factory.getCustomerByID. In this case, the factory function is posting and retrieving data via MVC/angular.$http.post. That all works fine but the subsequent actions in my controller function are executing before the .post is finished.
I've tried making either or both async/await but I think I'm not understanding how to do that. I've tried quite a few of the examples here and elsewhere with no luck.
I have a button that calls setOrderFromGrid which calls getCustomerById. I would assume that making controller.getCustomerById an async function would be the best way but I can't get it to work.
angular.module('aps').factory('TechSheetFactory',
function($http) {
return {
//The ajax that is called by our controller
ITS: function(onSuccess, onFailure) {
const rvtoken = $("input[name='__RequestVerificationToken']").val();
$http({
method: "post",
url: "/DesktopModules/MVC/TechSheetMaint/TechSheet/InitializeNew",
headers: {
"ModuleId": moduleId,
"TabId": tabId,
"RequestVerificationToken": rvtoken
}
}).then(onSuccess).catch(onFailure);
},
saveTechSheetAng: function(onSuccess, onFailure, techSheetInfo) {
alert(JSON.stringify(techSheetInfo));
const rvtoken = $("input[name='__RequestVerificationToken']").val();
$http.post("/DesktopModules/MVC/TechSheetMaint/TechSheet/SaveTechSheetAng",
JSON.stringify(techSheetInfo),
{
headers: {
"ModuleId": moduleId,
"TabId": tabId,
"RequestVerificationToken": rvtoken,
'Content-Type': 'application/json'
}
}).then(onSuccess).catch(onFailure);
} ,
getCustomerById: function(onSuccess, onFailure, customerSearchString) {
alert('factory getcustomerbyid: ' + customerSearchString);
const rvtoken = $("input[name='__RequestVerificationToken']").val();
$http.post("/DesktopModules/MVC/TechSheetMaint/TechSheet/GetCustomerById",
{custId:customerSearchString},
{
headers: {
"ModuleId": moduleId,
"TabId": tabId,
"RequestVerificationToken": rvtoken,
'Content-Type': 'application/json'
}
}).then(onSuccess).catch(onFailure);
}
};
});
angular.module('aps').controller('TechSheetCtl', ['TechSheetFactory','$scope', '$rootScope', '$http', '$interval', '$modal', '$log','uiGridConstants',
function (TechSheetFactory,$scope, $rootScope, $http, $interval, $modal, $log) {
/* -----------------SaveTechSheet ------------*/
$scope.saveTechSheet = function() {
if (!$scope.dvTechSheet.$valid) {
$scope.Message = "Form not complete.";
$scope.Status = false;
$scope.showErrors=true;
return;
}
alert($scope.TechSheetInfo.Customer.CustomerID);
if (JSON.stringify($scope.TechSheetInfo.Customer) !== JSON.stringify($scope.TechSheetInfoStatic.Customer) &&
$scope.TechSheetInfo.Customer.CustomerID !== 0) {
if (confirm("You've made changes to this Customer. Save them?") !== true) {
return;
}
}
if (JSON.stringify($scope.TechSheetInfo.WorkOrder) !== JSON.stringify($scope.TechSheetInfoStatic.WorkOrder) &&
$scope.TechSheetInfo.WorkOrder.WorkOrderID !== 0) {
if (confirm("You've made changes to this Work Order. Save them?") !== true) {
return;
}
}
successFunction = function(response) {
var data = response.data.Data;
alert(data);
var techSheet = data.techSheet;
alert(data.status);
if (data.status) {
alert("looks good");
$scope.Message = "";
$scope.showErrors = false;
$scope.TechSheetInfo = techSheet;
alert($scope.TechSheetInfo);
$scope.TechSheetInfoStatic = angular.copy(techSheet);
$rootScope.customerInfo = techSheet.Customer;
createpdf($scope);
} else {
if (response.message !== null) {
$scope.Status = datae.status;
$scope.showErrors = true;
$scope.Message = data.message;
}
}
};
failureFunction = function(data) {
console.log('Error' + data);
};
TechSheetFactory.saveTechSheetAng(successFunction, failureFunction,$scope.TechSheetInfo);
};
/* ----------End SaveTechSheet ---------*/
//------------Initialize a new tech sheet. This is the default action for the page load/refresh/discard changes/clear form
$scope.initializeTechSheet = function() {
$scope.TechSheetInfo = [];
$scope.TechSheetInfoStatic = [];
$scope.customerIDDisabled = false;
$scope.orderIDDisabled = false;
$rootScope.customerInfo = [];
$scope.WindowsPassword = "";
$scope.EmailPassword = "";
const successFunction = function(response) {
$scope.TechSheetInfo = response.data;
$rootScope.customerInfo = response.data.Customer;
$scope.TechSheetInfoStatic = angular.copy(response.data);
};
const failureFunction = function(response) {
//console.log('Error' + response.status);
};
TechSheetFactory.ITS(successFunction, failureFunction);
};
//end initializeTechSheet
$scope.getCustomerById = function(custId) {
const successFunction = function(response) {
alert("success");
$scope.TechSheetInfo.Customer = response.data;
$scope.TechSheetInfoStatic.Customer = angular.copy(response.data);
$rootScope.customerInfo = response.data;
$scope.customerIDDisabled = true;
};
const failureFunction = function(data) {
alert('getcustomer fail');
console.log('Error' + JSON.stringify(data));
};
TechSheetFactory.getCustomerById(successFunction, failureFunction, custId);
};
$scope.setOrderFromGrid = function(woInfo) {
$scope.getCustomerById(woInfo.CustomerID);
$scope.TechSheetInfo.WorkOrder = woInfo; //this line and the next are occurring before getCustomerById has completed
$scope.TechSheetInfoStatic.Customer = angular.copy($scope.TechSheetInfo.Customer);
$scope.orderIDDisabled=true;
$scope.dvTechSheet.$setPristine();
};
$scope.resetForm = function() {
if (!$scope.dvTechSheet.$pristine) {
if (!confirm("Discard Changes?")) {
return;
}
}
$scope.initializeTechSheet();
$scope.dvTechSheet.$setPristine();
};
}]);
You lose the advantage of the Promises so you can opt-in a Promise this way. (I do not recommend it)
From the top of head something like this:
// inject $q
$scope.getCustomerById = function(custId) {
const deferred = $q.defer()
const successFunction = function(response) {
$scope.TechSheetInfo.Customer = response.data;
$scope.TechSheetInfoStatic.Customer = angular.copy(response.data);
$rootScope.customerInfo = response.data;
$scope.customerIDDisabled = true;
deferred.resolve(); // can pass value if you like
};
const failureFunction = function(data) {
alert('getcustomer fail');
console.log('Error' + JSON.stringify(data));
deferred.reject();
};
TechSheetFactory.getCustomerById(successFunction, failureFunction, custId);
return deferred.promise;
};
/////////////
$scope.setOrderFromGrid = function(woInfo) {
const prom = $scope.getCustomerById(woInfo.CustomerID);
prom.then(()=>{
$scope.TechSheetInfo.WorkOrder = woInfo;
$scope.TechSheetInfoStatic.Customer =
angular.copy($scope.TechSheetInfo.Customer);
$scope.orderIDDisabled=true;
$scope.dvTechSheet.$setPristine();
})
};
Mentioned on the github repository #225 of angular-service-modal
But i don't have a $on on $rootScope, so that shouldn't be the problem.
(also included code below)
My modal is getting called multiple times on close/hiding. Eg. [http://beta.belgianbrewed.com/en/product/budweiser-24x30cl](Example page)
The file in question can be found on /assets/angular/controllers/ShopActionController.js
Any thoughts where the problem could be?
The code calls: showPopup(ProductId,'BuyImmediate') in ShopActionController.js
app.controller('ShopActionDialogController', ['$scope', 'CurrentProduct', function ($scope, CurrentProduct) {
$scope.CurrentProduct = CurrentProduct;
console.log("Dialog called and ...");
console.log(CurrentProduct);
//modal.element.modal();
//modal.close.then(function (result) {
// $scope.message = result ? "You said Yes" : "You said No";
//});
}]);
app.controller('ShopActionController', ['$rootScope', '$scope', '$injector', '$http', '$timeout', 'ModalService', 'EndpointService', 'ImageResizeService', 'hotkeys',
function ($rootScope, $scope, $injector, $http, $timeout, ModalService, EndpointService, ImageResizeService, hotkeys) {
$scope.Resize = ImageResizeService;
$scope.Amount;
$scope.InitAmount;
$scope.ProductId;
$scope.ProductVariantId;
$scope.OrderLineId;
$scope.isLoading = false;
$scope.isShown = true;
//$scope.addedToCart = false; //new - not implemented
$scope.inCartAmount = 0; //new - not implemented
$scope.inWishList = false;
$scope.Change = function (Amount) {
$scope.Amount += Amount;
}
$scope.showPopup = function (ProductId,action) {
EndpointService.searchProducts(undefined, 0, 1, ProductId).then(function (response) {
ModalService.showModal({
templateUrl: "ProductPopup.html",
controller: "ShopActionDialogController",
inputs: {
CurrentProduct: response.data[0]
}
}).then(function (modal) {
// The modal object has the element built, if this is a bootstrap modal
// you can call 'modal' to show it, if it's a custom modal just show or hide
// it as you need to.
// console.log("test");
modal.element.modal();
var args = {
Amount: $scope.Amount,
ProductId: response.data[0].Id,
ProductVariantId: response.data[0].ProductVariantId,
OrderLineId: undefined,
InitAmount : $scope.InitAmount
};
if (action != undefined) {
args.Action = action;
}
$rootScope.$broadcast('init', args);
$scope.Amount = $scope.InitAmount;
modal.element.on('hidden.bs.modal', function (e) {
// $scope.Amount = $scope.InitAmount;
console.log("hidden");
modal.element.remove();
// close(result, 200);
});
modal.close.then(function (result) {
// console.log("close");
$scope.Amount = $scope.InitAmount;
modal.element.remove();
// close(result, 200);
//ModalService.closeModals();
// $scope.message = result ? "You said Yes" : "You said No";
});
});
});
}
$scope.CurrentProduct;// = CurrentProduct;
$scope.initiated = false;
var initListener = $scope.$on('init', function (event,args) {
if (!$scope.initiated) {
$scope.Amount = args.Amount;
$scope.InitAmount = args.InitAmount;
$scope.ProductId = args.ProductId;
$scope.ProductVariantId = args.ProductVariantId;
$scope.OrderLineId = args.OrderLineId;
switch (args.Action)
{
case 'BuyImmediate':
$scope.AddToCart();
break;
case 'View':
break;
}
}
});
$scope.$on('$destroy', function () {
console.log("killing this scope");
initListener();
});
$scope.init = function (Amount, ProductId, ProductVariantId, OrderLineId) {
$scope.initiated = true;
$scope.Amount = Amount;
$scope.InitAmount = Amount;
$scope.ProductId = ProductId;
$scope.ProductVariantId = ProductVariantId;
$scope.OrderLineId = OrderLineId;
}
$scope.getSpecification = function (Product,SpecificationId, SpecificationName) {
var Spec = undefined;
angular.forEach(Product.Specifications, function (elem, i) {
if (elem.SpecificationCandidate.SpecificationId == SpecificationId ||
elem.SpecificationCandidate.Specification.Name == SpecificationName) {
Spec = elem.SpecificationCandidate;
}
});
return Spec;
}
$scope.isAddedInCart = function () {
return $scope.OrderLineId != undefined;
}
$scope.PriceInclusive = function (orderline) {
return orderline.Amount * orderline.Product.Price * 1.21;
}
$scope.PriceExclusive = function (orderline) {
return orderline.Amount * orderline.Product.Price;
}
$scope.bindKeys = function () {
hotkeys.add({
combo: '+',
description: 'Add 1 to ammount',
callback: function () {
$scope.Amount += 1;
}
});
hotkeys.add({
combo: '-',
description: 'Substract 1 from ammount',
callback: function () {
if ($scope.Amount > 0) {
$scope.Amount -= 1;
}
}
});
}
$scope.IncrementWith = function (Amount) {
var newAmount = $scope.Amount + Amount;
if (newAmount >= 0) {
$scope.Amount = newAmount;
}
}
$scope.ChangeSortBy = function (SortBy) {
console.log("Changing Sort By");
}
$scope.ChangePageSize = function (PageSize) {
console.log("Changing PageSize");
}
$scope.GetCart = function () {
return EndpointService.orderlines;
}
$scope.RemoveOrderLine = function ($event) {
$scope.isLoading = true;
EndpointService.removeOrderLine($scope.OrderLineId)
.then(function (response) {
EndpointService.orderlines = response.data;
$rootScope.$broadcast('DeleteOrderLine', { OrderLineId: $scope.OrderLineId });
$scope.isLoading = false;
$scope.isShown = false;
});
$event.preventDefault();
return false;
}
$scope.AddToWishlist = function () {
//AddToWishlist
EndpointService.addToWishList($scope.ProductId)
.then(function (response) {
//return true;
$scope.inWishList = true;
});
return false;
}
$scope.RemoveFromWishlist = function () {
EndpointService.removeFromWishList($scope.ProductId)
.then(function (response) {
//return true;
$scope.isShown = false;
});
return false;
}
$scope.PrepareAddOrderLineRequest = function (onlyBulk) {
if (!onlyBulk || (onlyBulk && $scope.InitAmount == 0 && $scope.InitAmount < $scope.Amount)) {
var request = EndpointService.UpdateAmountRequest;
request.OrderLineId = $scope.OrderLineId;
request.Amount = $scope.Amount;
request.ProductId = $scope.ProductId;
return request;
} else {
return undefined;
}
}
$scope.FocusAmountInput = function () {
if ($scope.Amount == $scope.InitAmount) {
$scope.Amount = "";
}
}
$scope.LeaveAmountInput = function () {
if ($scope.Amount == "") {
$scope.Amount = $scope.InitAmount;
}
}
$scope.$on("BroadCastBulkOrders", function () {
var request = $scope.PrepareAddOrderLineRequest(true);
if (request != undefined) {
$rootScope.$broadcast("AddBulkOrder", request);
$scope.Amount = $scope.InitAmount;
}
});
$scope.AddToCart = function () {
$scope.isLoading = true;
var request = $scope.PrepareAddOrderLineRequest(false);
EndpointService.updateAmount(request)
.then(function (response) {
EndpointService.orderlines = response.data;
$rootScope.$broadcast('BasketChanged');
angular.forEach(response.data, function (elem, i) {
if (elem.ProductId == $scope.ProductId) {
$scope.OrderLineId = elem.Id;
$scope.inCartAmount = elem.Amount;
}
});
$scope.Amount = $scope.InitAmount;
$scope.isLoading = false;
});
return false;
}
$scope.UpdateOrderLine = function () {
//$emit required values
$scope.isLoading = true;
var request = $scope.PrepareAddOrderLineRequest(false);
request.isFixed = true;
EndpointService.updateAmount(request)//$scope.OrderLineId, $scope.ProductId, $scope.Amount, true)
.then(function (response) {
angular.forEach(response.data, function (elem, i) {
if (elem.Id == $scope.OrderLineId) {
$rootScope.$broadcast('ChangeAmount', { OrderLineId: $scope.OrderLineId, Amount: $scope.Amount });
}
});
$scope.isLoading = false;
});
return false;
}
}]);
The service
app.service('EndpointService', ['$http', '$q', function ($http, $q) {
this.orderlines = new Array();
//search for products, standard paging included
this.searchProducts = function (searchTerm, page, pageSize, productId) {
var endPoint = "/api/Endpoint/SearchProducts?$expand=Tags,Specifications($expand=SpecificationCandidate($expand=Specification)),CoverPhoto";
if (searchTerm != undefined && searchTerm.length > 0) {
endPoint = endPoint + "&$filter=indexof(Title,'" + searchTerm + "') gt -1"; //make a var
} else if (productId !== undefined) {
{
endPoint = endPoint + "&$filter=Id eq " + productId + " "; //make a var
}
//endPoint = endPoint + "&$filter=";
}
endPoint = endPoint + "&$skip=0&$top=" + pageSize;
return $http.get(endPoint);
//.then(function (response) {
// //console.log(response.data);
// return response.data;
//})
}
// this.ShippingCost = $q.defer();
this.ShippingCost = new Object();
this.calculateShipping = function (address, shippingMethodId) {
if (address == undefined) {
return this.ShippingCost;
} else {
//https://appendto.com/2016/02/working-promises-angularjs-services/
//var deferred = $q.defer();
var endPoint = "/api/Endpoint/CalculateShippingCost?timestamp=" + Date.now();
return $http({
url: endPoint,
method: "GET",
params: {
DeliveryAddress: address,
ShippingMethodId: shippingMethodId,
timestamp: Date.now()
}
})
}
}
this.getOrderLines = function () {
var endPoint = "/api/Endpoint/GetOrder";
return $http({
url: endPoint,
method: "GET",
params: {
timestamp : Date.now()
}
})
.then(function (response) {
this.orderlines = response.data;
return this.orderlines;
});
}
this.removeOrderLine = function (OrderLineId) {
var endPoint = "/api/Endpoint/RemoveOrderLine";
return $http({
url: endPoint,
method: "POST",
params: {
OrderLineId: OrderLineId
}
});
}
this.addToWishList = function (ProductId) {
var endPoint = "/api/Endpoint/AddToWishlist";
return $http({
url: endPoint + "?ProductId=" + ProductId,
method: "GET"
});
}
this.removeFromWishList = function (ProductId) {
var endPoint = "/api/Endpoint/RemoveFromWishlist";
return $http({
url: endPoint + "?ProductId=" + ProductId,
method: "GET"
});
}
this.UpdateAmountRequest = {
ProductId: "",
Amount: 0,
OrderLineId: "",
isFixed : false
}
this.bulkUpdateAmount = function (request) {
var endPoint = "/api/Endpoint/BulkAddOrderLines";
return $http({
url: endPoint,
method: "POST",
headers: {
'Content-Type': "application/json"
},
data: request
});
}
this.updateAmount = function (request){//OrderLineId,ProductId, Amount, isFixed) {
var endPoint = "/api/Endpoint/AddOrderLine?timestamp="+ Date.now();
//console.log("hey, changing the amount " + Amount + " for product id " + ProductId + " are you? :) ");
return $http({
url: endPoint,
method: "POST",
headers: {
'Content-Type': "application/json"
},
data: request
});
}
}]);
You need to add your bootstrap modal hidden listener to the dialog controller context.
app.controller('ShopActionDialogController', ['$scope', '$element', 'CurrentProduct', 'close', function ($scope, $element, CurrentProduct, close) {
$scope.CurrentProduct = CurrentProduct;
console.log("Dialog called and ...");
console.log(CurrentProduct);
//modal.element.modal();
//modal.close.then(function (result) {
// $scope.message = result ? "You said Yes" : "You said No";
//});
//listen for when the modal is dismissed and resolve the ModalService Close promise
$element.on('hidden.bs.modal', function (e) {
close({
currentProduct: CurrentProduct
}, 200); // close, but give 200ms for bootstrap to animate
});
}]);
Note that $element and close were added to the controller dependencies.
I am trying to understand Angular's promises and scopes. Actually I implemented the directive bellow. The thing that I want to do is to receive images from server and store locally in order to cache them for next times. Also I want to show a spinner before the load of image is completed and show it after the completion.
How can update variable newUrl into directive when completed all of these promises?
Do you have any idea?
My HTML code is:
<div style="text-align: center;"
cache-src
url="https://upload.wikimedia.org/wikipedia/commons/c/c0/Aix_galericulata_(Male),_Richmond_Park,_UK_-_May_2013.jpg">
</div>
My directive is:
.directive('cacheSrc', [function () {
return {
restrict: 'A',
scope: {
url: '#'
},
controller: 'cacheSrcCtrl',
template: '<img width="100%" ng-if="newUrl!=null" src="{{newUrl}}"><ion-spinner ng-if="newUrl==null" icon="spiral"></ion-spinner>',
};
}])
And the controller of directive has the function bellow:
document.addEventListener('deviceready', function () {
$scope.updateUrl = function (newUrl) {
$scope.newUrl = newUrl;
};
var tmp = $scope.url;
$cordovaSQLite.execute(db, 'SELECT * FROM images where url = (?)', [tmp])
.then(function (result) {
if (result.rows.length > 0) {
$scope.exists = true;
for (var i = 0; i < res.rows.length; i++) {
var image = {
id: res.rows.item(i).id,
url: res.rows.item(i).url,
uri: res.rows.item(i).uri
};
$scope.updateUrl(image.uri);
}
} else {
$scope.exists = false;
var fileTransfer = new FileTransfer();
var uri = encodeURI(tmp);
var uriSave = '';
var fileURL = cordova.file.dataDirectory + uri;//'kaloudiaImages';// + getUUID();// + "DCIM/myFile";
fileTransfer.download(
uri, fileURL, function (entry) {
uriSave = entry.toURL();
KaloudiaDB.add(tmp, fileURL);
$scope.newUrl = fileURL;
$scope.updateUrl(fileURL);
},
function (error) {
console.log("download error code" + error.code);
},
false, {
headers: {
// "Authorization": "Basic dGVzdHVzZXJuYW1lOnRlc3RwYXNzd29yZA=="
}
}
).then(function (data) {
$scope.newUrl = fileURL;
});
}
}, function (error) {
$scope.statusMessage = "Error on saving: " + error.message;
})
.then(function (data) {
$scope.$apply(function () {
$scope.newUrl = fileURL;
});
});
});
var appModule = angular.module('myApp', [ 'angular-storage', 'ui.router' ]);
appModule
.controller(
'MainCtrl',
[
'mainService','$scope','$http','userFactory','$state','$rootScope','store',
function(mainService, $scope, $http, userFactory, $state,$rootScope,store) {
$scope.token = null;
$scope.error = null;
$scope.user={"emailId":"","password":""};
$scope.login = function(user) {
$scope.error = null;
mainService
.login(user)
.then(
function(token) {
$scope.token = token;
$http.defaults.headers.common.Authorization = 'Bearer '
+ token;
userFactory.setUserToken(token);
console.log("token store");
$state.go("home");
}, function(error) {
$scope.error = error
$scope.userName = '';
alert("not");
});
}
$scope.loggedIn = function() {
return store.get("token") !== null;
}
} ]);
appModule.controller('HomeCtrl',['$scope','mainService','$http','userFactory','$state',function($scope,mainService,$http,userFactory,$state){
$scope.greeting = 'Welcome to the JSON Web Token / AngularJR / Spring example!';
$scope.roleUser = false;
$scope.roleAdmin = false;
$scope.roleFoo = false;
// $scope.checkRoles = function() {
mainService.hasRole('user').then(
function(user) {
console.log(user + " user");
$scope.roleUser = user
});
mainService.hasRole('admin').then(
function(admin) {
console.log(admin + " admin");
$scope.roleAdmin = admin
});
mainService.hasRole('foo').then(function(foo) {
$scope.roleFoo = foo
});
// }
$scope.logout = function() {
$scope.userName = '';
$scope.token = null;
$http.defaults.headers.common.Authorization = '';
userFactory.removeUserToken();
$state.go("login");
}
}]);
appModule.config([ '$stateProvider', '$urlRouterProvider',
function($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise("/login");
$stateProvider.state('login', {
url : "/login",
templateUrl : "login.html",
controller : 'MainCtrl'
}).state('home', {
url : "/home",
templateUrl : "home.html",
controller : 'HomeCtrl'
});
} ]);
appModule.config([ '$httpProvider', function($httpProvider) {
$httpProvider.interceptors.push('myInterceptor');
} ]);
appModule.factory('myInterceptor', function(store,userFactory) {
var myInterceptor = {
request : function(request) {
if(userFactory.getUserToken() !=null){
request.headers['Authorization'] = 'Bearer '+ userFactory.getUserToken();
return request;
}
return request;
},
response : function(response) {
return response;
}
};
return myInterceptor;
});
appModule.run(function(mainService,$state,$rootScope) {
$rootScope.$on('$stateChangeStart', function (event, next) {
var is=mainService.auth();
if(is == false && next.name=="home"){
event.preventDefault();
$state.go("login");
}
});
});
appModule.factory('userFactory',['store',function(store){
var user={};
user.setUserToken=function(token){
store.set("token",token);
},
user.getUserToken=function(){
return store.get("token");
},
user.removeUserToken=function(){
store.remove("token");
}
return user;
}]);
appModule.service('mainService', function($http, userFactory) {
return {
login : function(user) {
var config={
method:'POST',
url:'http://192.168.0.5:8080/TeamAssist/camelRestlet/getLoginDetails?restletMethod=post'
};
return $http(config, user).then(function(response) {
console.log(response);
return response.data.token;
});
},
hasRole : function(role) {
return $http.get('/api/role/' + role).then(function(response) {
console.log(response);
return response.data;
});
},
auth : function() {
if (userFactory.getUserToken() == null)
return false;
else
return true;
}
};
});var appModule = angular.module('myApp', [ 'angular-storage', 'ui.router' ]);
appModule
.controller(
'MainCtrl',
[
'mainService','$scope','$http','userFactory','$state','$rootScope','store',
function(mainService, $scope, $http, userFactory, $state,$rootScope,store) {
$scope.token = null;
$scope.error = null;
$scope.user={"emailId":"","password":""};
$scope.login = function(user) {
$scope.error = null;
mainService
.login(user)
.then(
function(token) {
$scope.token = token;
$http.defaults.headers.common.Authorization = 'Bearer '
+ token;
if(token.length<=10)
{
$scope.token = '';
$http.defaults.headers.common.Authorization = '';
$state.go('login');
return;
}
userFactory.setUserToken(token);
console.log("token store");
$state.go("home");
}, function(error) {
$scope.error = error
$scope.userName = '';
alert("not");
});
}
$scope.loggedIn = function() {
return store.get("token") !== null;
}
} ]);
appModule.controller('HomeCtrl',['$scope','mainService','$http','userFactory','$state',function($scope,mainService,$http,userFactory,$state){
$scope.greeting = 'Welcome to the JSON Web Token / AngularJR / Spring example!';
$scope.roleUser = false;
$scope.roleAdmin = false;
$scope.roleFoo = false;
// $scope.checkRoles = function() {
mainService.hasRole('user').then(
function(user) {
console.log(user + " user");
$scope.roleUser = user
});
mainService.hasRole('admin').then(
function(admin) {
console.log(admin + " admin");
$scope.roleAdmin = admin
});
mainService.hasRole('foo').then(function(foo) {
$scope.roleFoo = foo
});
// }
$scope.logout = function() {
$scope.userName = '';
$scope.token = null;
$http.defaults.headers.common.Authorization = '';
userFactory.removeUserToken();
$state.go("login");
}
}]);
appModule.config([ '$stateProvider', '$urlRouterProvider',
function($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise("/login");
$stateProvider.state('login', {
url : "/login",
templateUrl : "login.html",
controller : 'MainCtrl'
}).state('home', {
url : "/home",
templateUrl : "home.html",
controller : 'HomeCtrl'
});
} ]);
appModule.config([ '$httpProvider', function($httpProvider) {
$httpProvider.interceptors.push('myInterceptor');
} ]);
appModule.factory('myInterceptor', function(store,userFactory) {
var myInterceptor = {
request : function(request) {
if(userFactory.getUserToken() !=null){
request.headers['Authorization'] = 'Bearer '+ userFactory.getUserToken();
return request;
}
return request;
},
response : function(response) {
return response;
}
};
return myInterceptor;
});
appModule.run(function(mainService,$state,$rootScope) {
$rootScope.$on('$stateChangeStart', function (event, next) {
var is=mainService.auth();
if(is == false && next.name=="home"){
event.preventDefault();
$state.go("login");
}
});
});
appModule.factory('userFactory',['store',function(store){
var user={};
user.setUserToken=function(token){
store.set("token",token);
},
user.getUserToken=function(){
return store.get("token");
},
user.removeUserToken=function(){
store.remove("token");
}
return user;
}]);
appModule.service('mainService', function($http, userFactory) {
return {
login : function(user) {
var config={
method:'GET',
url:'http://192.168.0.64:8080/TeamAssist/rest/service/login/'+ user.emailId + '/' + user.password,
headers: {
'Content-Type': 'application/json'
}
};
return $http(config, user).then(function(response) {
console.log(response);
return response.data;
});
},
hasRole : function(role) {
return $http.get('/api/role/' + role).then(function(response) {
console.log(response);
return response.data;
});
},
auth : function() {
if (userFactory.getUserToken() == null)
return false;
else
return true;
}
};
});
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<form ng-submit="login(user)">
Username: <input type="text" ng-model="user.emailId" /><br/>
Password: <input type="text" ng-model="user.password" /><span><input
type="submit" value="Login" />
</form>
</body>
</html>
After successfully login and logout, when I do login again with correct credentials, I got "****Request header field Authorization is not allowed by Access-Control-Allow-Headers**.**" error, but if I refresh the page then I get successfully logged-IN.
I am just beginning to learn AngularJS and have a problem understanding promises. I have
factory which makes call to back-end server and returns a promise as follows:
var commonModule = angular.module("CommonModule", [])
.factory('AjaxFactory', function($http, $q, $dialogs, transformRequestAsFormPost) {
return {
post: function(reqUrl, formData) {
var deferred = $q.defer();
$http({
method: "post",
url: reqUrl,
transformRequest: transformRequestAsFormPost,
data: formData
}).success(function(data) {
if (data['error']) {
if (data['message']) {
$dialogs.notify('Error', data['message']);
} else {
}
} else if (data['success']) {
if (data['message']) {
$dialogs.notify('Message', data['message']);
}
} else if (data['validation']) {
}
deferred.resolve(data);
}).error(function(data) {
$dialogs.notify('Error', 'Unknown Error. Please contact administrator');
});
return deferred.promise;
}
};
})
.factory("transformRequestAsFormPost", function() {
function transformRequest(data, getHeaders) {
var headers = getHeaders();
headers[ "Content-type" ] = "application/x-www-form-urlencoded; charset=utf-8";
return(serializeData(data));
}
return(transformRequest);
function serializeData(data) {
if (!angular.isObject(data)) {
return((data === null) ? "" : data.toString());
}
var buffer = [];
for (var name in data) {
if (!data.hasOwnProperty(name)) {
continue;
}
var value = data[ name ];
buffer.push(
encodeURIComponent(name) +
"=" +
encodeURIComponent((value === null) ? "" : value)
);
}
var source = buffer
.join("&")
.replace(/%20/g, "+")
;
return(source);
}
}
);
I have a controller which calls the AjaxFactory service using two functions as follows
marketingCampaignModule.controller('CampaignInfoController', ['$scope', 'AjaxFactory', '$state', 'campaign', function($scope, AjaxFactory, $state, campaign) {
$scope.init = function() {
$scope.name = campaign['name'];
$scope.description = campaign['description'];
console.log($scope.mcmcid);
if ($scope.mcmcid > 0) {
var inputData = {};
inputData['mcmcid'] = $scope.mcmcid;
var ajaxPromise1 = AjaxFactory.post('index.php/mcm/infosave/view', inputData);
ajaxPromise1.then(function(data) {
if (data['success']) {
$scope.name = data['params']['name'];
$scope.description = data['params']['description'];
}
},
function(data) {
if (data['success']) {
$scope.name = data['params']['name'];
$scope.description = data['params']['description'];
}
}
);
}
};
$scope.init();
$scope.submitForm = function(isValid) {
if (isValid) {
var formData = $scope.prepareFormData();
var ajaxPromise = AjaxFactory.post('index.php/mcm/infosave/save', formData);
ajaxPromise.then(function(data) {
if (data['success']) {
$scope.setValues(data['params']);
} else if ('validation') {
$scope.handleServerValidationError(data['message']);
}
});
}
};
$scope.prepareFormData = function() {
mcmcId = '';
var formData = {};
if ($scope.mcmcid > 0) {
mcmcId = $scope.mcmcid;
}
formData["mcmcid"] = mcmcId;
formData["name"] = $scope.name;
formData["description"] = $scope.description;
return formData;
};
$scope.setValues = function(data) {
$scope.mcmcid = data['mcmcid'];
$state.go('TabsView.Companies');
};
$scope.handleServerValidationError = function(validationMessages) {
alert(validationMessages['name']);
};
}]);
The promise ajaxPromise gets resolved in the function $scope.submitform but not in $scope.init.
Please tell me what am I missing.
add to your service deffere.reject() on error:
app.factory('AjaxFactory', function($http, $q, $dialogs, transformRequestAsFormPost) {
return {
post: function(reqUrl, formData) {
var deferred = $q.defer();
$http({
method: "post",
url: reqUrl,
transformRequest: transformRequestAsFormPost,
data: formData
}).success(function(data) {
if (data['error']) {
if (data['message']) {
$dialogs.notify('Error', data['message']);
} else {
}
} else if (data['success']) {
if (data['message']) {
$dialogs.notify('Message', data['message']);
}
} else if (data['validation']) {
}
deferred.resolve(data);
}).error(function(data) {
deferred.reject(data)
$dialogs.notify('Error', 'Unknown Error. Please contact administrator');
});
return deferred.promise;
}
};
});
and in you controller handle error:
$scope.init = function () {
$scope.name = campaign['name'];
$scope.description = campaign['description'];
console.log($scope.mcmcid);
if ($scope.mcmcid > 0) {
var inputData = {};
inputData['mcmcid'] = $scope.mcmcid;
var ajaxPromise1 = AjaxFactory.post('index.php/mcm/infosave/view', inputData);
ajaxPromise1.then(function (data) {
if (data['success']) {
$scope.name = data['params']['name'];
$scope.description = data['params']['description'];
}
},
function (data) {
if (data['success']) {
$scope.name = data['params']['name'];
$scope.description = data['params']['description'];
}
},
//on error
function (data) {
alert("error");
console.log(data);
});
}
};