Problem with upload file with a formGroup - javascript

I am using angular to make a register form include some information(name, email, password, and avatar). Backend I am using NodeJS and MongoDB to store information. About backend I already wrote register API OK. I tested on postman, It's worked for backend!!
But in angular client, when I input information from my register form, It's appear error, I am using formData to send input form to Backend API.
I am using formGroup to send my usersystem object include (name, role, email, password, and avatar)
Here is my html file.
<div class="common-form float_left ">
<form [formGroup]="dialogRegisterUserSysForm" >
<div class="field_wrapper box FlowupLabels">
<label class="label">NAME</label>
<div class="field fl_wrap pad-top-0">
<input type="text" name="name" formControlName="name" maxlength="255" placeholder="Enter user system name" autocomplete="off" role="textbox" aria-autocomplete="list" aria-haspopup="true">
</div>
<div class="clr"></div>
</div>
<div class="field_wrapper box FlowupLabels">
<label class="label">PASSWORD</label>
<div class="field fl_wrap pad-top-0">
<input type="password" id="illness-name" class="input-big hc_name fl_input ui-autocomplete-input" name="password" formControlName="password" maxlength="255" placeholder="Please enter a password" autocomplete="off" role="textbox" aria-autocomplete="list" aria-haspopup="true">
</div>
<div class="error_field" id="testResultsErrors"></div> <div class="clr"></div>
</div>
<div class="field_wrapper box FlowupLabels">
<label class="label">EMAIL</label>
<div class="field fl_wrap pad-top-0">
<input type="text" id="illness-name" class="input-big hc_name fl_input ui-autocomplete-input" name="email" formControlName="email" maxlength="255" placeholder="Enter an email." autocomplete="off" role="textbox" aria-autocomplete="list" aria-haspopup="true">
</div>
<div class="error_field" id="testResultsErrors"></div> <div class="clr"></div>
</div>
<div>
<label>Upload Avatar</label>
<input (change)="onFileSelect($event.target)" type="file" formControlName="avatar" class="form-control">
</div>
<div class="save-cancel-btngrp-wrap">
<div class="cancel-link switchToViewMode" style="float: right">
<a (click)="matDialogRef.close(dialogRegisterUserSysForm)" class="switchToViewMode btn flat">CANCEL</a>
</div>
<div *ngIf="action =='new'" class="cancel-link switchToViewMode" style="float: right">
<a (click)="matDialogRef.close(['save',dialogRegisterUserSysForm])" class="switchToViewMode btn flat">SAVE</a>
</div>
</div>
</form>
</div>
In this form, the avatar is file input, I wrote “onFileSelect(input)” method.
onFileSelect(input) {
var fInput = input.files[0];
var fileName = fInput.name;
alert(fileName);
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = (e: any) => {
alert("Result: " + e.target.result);
this.userSys.avatar = e.target.result;
// reader.readAsDataURL(input.files[0]);
}
// this.userSys.avatar = e.target.result;
reader.readAsDataURL(input.files[0]);
}
}
And below is my ts file.
import { FormBuilder, FormGroup } from '#angular/forms';
import { MAT_DIALOG_DATA, MatDialogRef } from '#angular/material';
import { UserSysService } from '../usersys.service';
import { UserSysModel } from '../usersys.model';
import { Subject } from 'rxjs';
import { takeUntil } from 'rxjs/operators';
#Component({
selector : 'usersys-form-dialog',
templateUrl : './usersys-form.component.html',
styleUrls : ['./usersys.component.scss'],
encapsulation: ViewEncapsulation.None
})
export class UserSysFormDialogComponent
{
action: string;
userSys: UserSysModel; // Medical report model
dialogRegisterUserSysForm: FormGroup;
dialogTitle: string;
/**
* Constructor
*
* #param {MatDialogRef<MedicalReportFormDialogComponent>} matDialogRef
* #param _data
* #param {FormBuilder} _formBuilder
*/
constructor(
// private _mrReportService: HealthMedicalReportService,
public matDialogRef: MatDialogRef<UserSysFormDialogComponent>,
#Inject(MAT_DIALOG_DATA) private _data: any,
private _formBuilder: FormBuilder
)
{
// this.dialogTitle = 'Add New Medical Report';
// set default here
this.action = this._data.action;
if(this.action === 'edit'){
this.dialogTitle = 'Edit User System';
this.userSys = _data.userSys;
}else{
this.dialogTitle = 'Register new User System';
this.userSys = new UserSysModel({});
}
this.dialogRegisterUserSysForm = this.createUserSystemDialogForm();
}
onFileSelect(input) {
var fInput = input.files[0];
var fileName = fInput.name;
alert(fileName);
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = (e: any) => {
alert("Result: " + e.target.result);
this.userSys.avatar = e.target.result;
// reader.readAsDataURL(input.files[0]);
}
// this.userSys.avatar = e.target.result;
reader.readAsDataURL(input.files[0]);
}
}
/**
* Create UserSystem form
*
* #returns {FormGroup}
*/
createUserSystemDialogForm(): FormGroup
{
return this._formBuilder.group({
email : [this.userSys.email],
password : [this.userSys.password],
name : [this.userSys.name],
avatar : [this.userSys.avatar]
});
}
}
Below is image of my register form:
But I got the error “fakepath”, I cannot post this form to the server.
I think my english is not good so may be my explain is so hard to understand.
Thanks you so much

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/modernizr/2.8.2/modernizr.js"></script>
<script>
window.onload = function () {
document.getElementById("uploadfile").disabled = true;
document.getElementById("excelData").disabled = false;
};
document.addEventListener('keydown', function (e) {
if (e.which == 116) {
window.onbeforeunload = function () {
window.onbeforeunload = null;
$(".se-pre-con").fadeIn("slow");
}
}
}, false);
$(document).ready(function () {
$(".se-pre-con").fadeOut("slow");;
});
function LoadPreloder() {
$(".se-pre-con").fadeIn("slow");;
}
function UnloadPreloder() {
$(".se-pre-con").fadeOut("slow");;
}
function enableDisable() {
var FileSelectedValue = null;
var ClassSelected = 0;
FileSelectedValue = document.getElementById("excelData").value;
ClassSelected = document.getElementById("SelectedClass").value;
//alert(ClassSelected);
if (document.getElementById("excelData").files.length) {
// alert("File is Selected !!");
document.getElementById("uploadfile").disabled = false;
}
else if (!document.getElementById("excelData").files.length) {
//alert("No File Selected !");
document.getElementById("uploadfile").disabled = true;
}
}
</script>
#section AngularScripts{
<script type="text/javascript">
var schoolStuff = angular.module("schoolStuff", ['lr.upload']);
schoolStuff.controller("downloadDataformateController", ['$scope', 'upload', '$http', function ($scope, upload, $http) {
$http.get('#Url.Action("GetStandardDivisionList", "Collection")')
.then(function (response) {
$scope.Standard_Mapping_Division = response.data;
// $scope.Standard_Mapping_DivisionId = $scope.Standard_Mapping_Division[0].Standard_Mapping_DivisionId;
$scope.dataType = [
{ "dataTypeId": "1", "dataTypeValue": "Student" },
{ "dataTypeId": "2", "dataTypeValue": "Teacher" }
];
$scope.dataTypeId = $scope.dataType[0].dataTypeId;
$scope.showdragdrop = null;
});
$scope.uploadExcel = function () {
LoadPreloder();
if ($scope.dataFile != undefined) {
upload({
url: '#Url.Action("PostExcelStudent", "ManageExcelData")',
method: 'POST',
data: {
standard_mapping_divisionId: $scope.Standard_Mapping_DivisionId,
typeId: $scope.dataTypeId,
dataFile: $scope.dataFile
}
}).then(function (response) {
alert(response.data.Message);
$scope.UploadedStudentData = response.data.studentsdata;
UnloadPreloder();
});
}
}
$scope.changeme = function () {
//alert($scope.showdragdrop);
//enableDisable();
$scope.showdragdrop = 1;
// alert($scope.showdragdrop);
}
$scope.uploadStudentData = function () {
LoadPreloder($scope.UploadedStudentData);
console.log()
$http({
url: '#Url.Action("UploadStudentData", "ManageExcelData")',
method: 'POST',
data: {
standard_mapping_divisionId: $scope.Standard_Mapping_DivisionId,
studentData: $scope.UploadedStudentData
}
}).then(function (response) {
$scope.InsertedStudentData = response.data.studentsdata;
if (($scope.InsertedStudentData).length != 0) {
UnloadPreloder();
$scope.UploadedStudentDataNull = null;
$('html, body').animate({ scrollTop: $('#InseertedStudentRecord').offset().top }, 'slow');
//console.log(response);
//alert(response.data.Message);
//alert(response.data.teachersdata);
//alert(response.data.Success);
$scope.InsertedStudentData = response.data.studentsdata;
if (response.data.Success != 0) {
if (($scope.InsertedStudentData).length != 0) {
UnloadPreloder();
$scope.UploadedStudentDataNull = null;
$('html, body').animate({ scrollTop: $('#InseertedStudentRecord').offset().top }, 'fast');
}
else if (($scope.InsertedStudentData).length == 0) {
$scope.UploadedTeacherDataNull = 0;
UnloadPreloder();
// alert($scope.UploadedTeacherDataNull);
}
}
else if (response.data.Success == 0) {
alert(response.data.Message);
UnloadPreloder();
}
}
else if (($scope.InsertedStudentData).length == 0) {
$scope.UploadedStudentDataNull = 0;
UnloadPreloder();
// alert($scope.UploadedTeacherDataNull);
}
UnloadPreloder();
});
}
}]).directive('uploadFile', ['$parse', function ($parse) {
return {
restrict: 'A',
link: function (scope, element, attrs) {
var file_uploaded = $parse(attrs.uploadFile);
element.bind('change', function () {
scope.$apply(function () {
file_uploaded.assign(scope, element[0].files[0]);
});
});
}
};
}]);
</script>
}

Remove formControlName form file input then in your onload function set the value of avatar control. You need a instance of ChangeDetectorRef as well.
this.formGroup.patchValue({
avatar: reader.result
});
// Mark dirty
this.cdRef.markForCheck();
Note: In this approach as a value you'll have BASE64 hash which you should decrypt on the server side.

Related

Changed email address will not be forwarded from one to the other in AngularJS

I have a form, where an email address is "saved":
It derives from the following code:
'use strict';
angular.module('app').factory('Emails', function ($window)
{
var DEFAULT = 'change-it#something.com';
var data = $window.eval($window.localStorage.getItem('emailaddress')) || DEFAULT;
var Emails = {};
Emails.get = function ()
{
return data;
};
Emails.set = function (emailaddress)
{
data = emailaddress;
$window.localStorage.setItem('emailaddress', $window.JSON.stringify(data));
};
return Emails;
});
When clicking on the button for the email address a new form opens:
The code for this popup (email-popup.html) is the following:
<p>Email-Adresse eingeben</p>
<form name="emailForm">
<div class="rules__popup">
<input type="email" name="input" ng-model="emailaddress" min="1" maxlength="30"
ng-change="updateEmail" required ng-keypress="positiveInteger($event)" ng-controller="PdfsmtpCtrl">
</div>
</form>
But when changing the email address herein and clicking the "OK-button" on top right, nothing happens. The email address remains the same!
To be complete, here is the code, where all starts and ends:
use strict';
angular.module('app')
.controller('PdfsmtpCtrl', function ($scope, Pdfsmtp, Emails, $ionicPopup, $window)
{
$scope.emailaddress = Emails.get();
$scope.changeEmail = function (emailaddress)
{
//var regex = /^[_a-z0-9]+(\.[_a-z0-9]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/;
var regex = /^(([^<>()\[\]\.,;:\s#\"]+(\.[^<>()\[\]\.,;:\s#\"]+)*)|(\".+\"))#(([^<>()[\]\.,;:\s#\"]+\.)+[^<>()[\]\.,;:\s#\"]{2,})$/i;
var popupScope = $scope.$new();
popupScope.emailForm
{
name: $scope.emailaddress
};
$ionicPopup.prompt
({
cssClass: 'rules__popup',
templateUrl: 'pdfsmtp/email-popup.html',
scope: $scope,
buttons:
[
{
text: 'OK',
type: 'button-balanced',
onTap: function (e)
{
//if (isNaN($scope.emails[email]))
if ($scope.emailaddress === undefined && isNaN($scope.emailaddress))
{
$scope.$emit('toast', 'Keine gültige Email-Adresse!');
e.preventDefault();
$scope.emailaddress = "change-it#something.com";
}
else if (!$scope.emailaddress.match(regex))
{
$scope.$emit('toast', 'Keine gültige Email-Adresse!');
e.preventDefault();
$scope.emailaddress = "change-it#something.com";
}
}
}
]
}).then(function ()
{
if ($window.cordova && $window.cordova.plugins.Keyboard)
{
$window.cordova.plugins.Keyboard.close();
}
});
};
$scope.save = function ()
{
Emails.set($scope.emailaddress);
$scope.emailsModal.hide();
};
What is going wrong here?

upload multiple file(image, file text,etc) to server using reactive form

Hi I want to upload multiple file and send them to a server: using reactive form:
I define this in the appropriate class:
this.attachmentsForm = this.formBuilder.group({
attachmentName: ['']
});
in the template html :
<form [formGroup]="attachmentsForm">
<ion-item>
<ion-label floating>
Attachment Name
</ion-label>
<ion-input type="text" formControlName="attachmentName"></ion-input>
</ion-item>
<input class="form-control" #fileInput type='file' (change)="fileChanged($event)">
</form>
In this class I used this function :
fileChanged(event) {
if (event.target.files && event.target.files[0]) {
if (event.target.files[0].size > 512000) {
this.fileValid = false;
let toast = this.toastCtrl.create({
message: 'the file size more than 500kb',
duration: 3000
});
toast.present();
} else {
this.fileValid = true;
}
}
}
So how can I get the data of the attachments :(Base64 or if there another solution)
thanks in advance
Please Try this code
imageBase64:string;
file: File;
fileChanged($event: any) {
if (event.target.files && event.target.files[0]) {
this.file = event.target.files[0];
if (this.file.size > 512000) {
if (this.file.type.startsWith("image")){
var myReader:FileReader = new FileReader();
myReader.onloadend = (e) => {
this.imageBase64 = myReader.result;
}
myReader.readAsDataURL(this.file);
}else {
Logger.error("must select an image.");
}
} else {
this.fileValid = true;
}
}
}
It may work.
files: FileList;
onChange(event: EventTarget) {
let eventObj: MSInputMethodContext = <MSInputMethodContext>event;
let target: HTMLInputElement = <HTMLInputElement>eventObj.target;
this.files = target.files;
}
sendFilesToServer() {
var formData = new FormData();
for (var i = 0; i < this.files.length; i++) {
formData.append('filesList[]', this.files[i], this.files[i].name);
}
var xhr = new XMLHttpRequest();
xhr.open('POST', "submitFiles");
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
console.log("Files Uploaded")
}
}
xhr.send(formData);
}
Java Code
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.apache.commons.io.IOUtils;
#Controller
public class MyController {
#ResponseBody
#RequestMapping(value = "submitFiles", method = RequestMethod.POST)
public String submitPapers(MultipartHttpServletRequest request) {
List papers = request.getFiles("filesList");
// If "filesList" doesn't work then try "filesList[]"
try {
saveFilesToServer(papers);
} catch (Exception e) {
return "error";
}
return "success";
}
public void saveFilesToServer(List multipartFiles) throws IOException {
String directory = "/home/user/uploadedFilesDir/";
File file = new File(directory);
file.mkdirs();
for (MultipartFile multipartFile : multipartFiles) {
file = new File(directory + multipartFile.getOriginalFilename());
IOUtils.copy(multipartFile.getInputStream(), new FileOutputStream(file));
}
}
}
Even if it will not work then try the
classic method
**NOTE : ** In html code don't forget to add attribute multiple in element.
<input name="papers" id="modalPapers" type="file" class="filestyle" multiple data-input="false">

modalinstance inject view model to update

I am using Modal popups to list out accounts details (accno and name). once row is selected from list view model variable(vm.vismaDebitAccount) need to update which is dynamic. In actual scenario popup will be open on textbox onclick and once row is selected from popup relevant textbox text should be update with account name. The view model variable(a particular textbox binding) should be able to inject to modalinstance result without hard cord things.
Here is my code.
my problem is why vm.vismaDebitAccount is not getting update? Please help me.
Here is the place on UI binding
<tr ng-repeat="accEntry in vm.vismaAccEntries">
<td>{{accEntry.invoiceNo}}</td>
<td><input type="text" ng-model='accEntry.debitAccNo' required name="field" ng-click="vm.openVismaAccModal('debit')" /></td>
<td><input type="text" ng-model='accEntry.debitVat' required name="field" /></td>
<td><input type="text" ng-model='accEntry.creditAccNo' required name="field" ng-click="vm.openVismaAccModal('credit')"/></td>
<td><input type="text" ng-model='accEntry.creditVat' required name="field" /></td>
<td>{{accEntry.amount}}</td>
<td>{{accEntry.voucherDate}}</td>
<td>{{accEntry.dueDate}}</td>
app.controller('invoiceCodeController', ['$routeParams', 'invoiceService', 'vismaService', '$uibModal', '$log', function ($routeParams, invoiceService, vismaService, $uibModal, $log) {
var vm = this;
var vismaDebitAccount = {
catogory: '',
account: ''
}
var vismaCreditAccount = {
catogory: '',
account: ''
}
vm.openVismaAccModal = function (accountType) {
console.log('hi before')
var modalInstance = $uibModal.open({
templateUrl: 'accountPopup.html',
controller: 'vismaAccController as vm'
});
modalInstance.result.then(function (selectedAccount) {
if (accountType === 'debit') {
vm.vismaAccEntries[0].debitAccNo = selectedAccount.account.No;
}
if (accountType === 'credit') {
vm.vismaAccEntries[0].creditAccNo = selectedAccount.account.No;
}
}, function () {
$log.info('Modal dismissed at: ' + new Date());
});
}
}]);
app.controller('vismaAccController', ['vismaService', '$uibModalInstance', function (vismaService, $uibModalInstance) {
var vm = this;
var selectedAcc = {
category: '',
account: ''
};
Init();
function Init() {
getVismaAccData();
}
vm.tabChange = function (e) {
if (e.target.nodeName === 'A') {
e.preventDefault();
}
}
vm.rowSelect = function (index, debitAcc, flag) {
selectedAcc.category = flag;
selectedAcc.account = debitAcc;
}
vm.ok = function () {
$uibModalInstance.close(selectedAcc);
};
vm.cancel = function () {
$uibModalInstance.dismiss('cancel');
};
function getVismaAccData() {
var errors = [];
vismaService.getSuppliers().then(function (data) {
vm.vismaSuppliers = data;
},
function (errorMsg) {
errors.push('<li>' + errorMsg + '</li>');
vm.savedSuccessfully = false;
});
vismaService.getCustomers()
.then(function (data) {
vm.vismaCustomers = data;
},
function (errorMsg) {
errors.push('<li>' + errorMsg + '</li>');
vm.savedSuccessfully = false;
});
vismaService.getGeneralLedger()
.then(function (data) {
vm.vismaGL = data;
},
function (errorMsg) {
errors.push('<li>' + errorMsg + '</li>');
vm.savedSuccessfully = false;
});
if (errors.length > 0) {
vm.message = errors.join(' ');
}
}
}]);

Using Breeze With Web Api And Angular js

i want to select item from drop down list and then i will see selected customer data in input
then iwant to edit inputs and then save them in database by breez js and web api
I have Web Api Controller like This :
[BreezeController]
public class ZzaController : ApiController
{
readonly EFContextProvider<ZzaDbContext> _contextProvider =
new EFContextProvider<ZzaDbContext>();
// ~/breeze/Zza/Metadata
[HttpGet]
public string Metadata()
{
return _contextProvider.Metadata();
}
// ~/breeze/Zza/Customers
[HttpGet]
public IQueryable<Customer> Customers()
{
var customers = _contextProvider.Context.Customers;
return customers;
}
// ~/breeze/Zza/SaveChanges
[HttpPost]
public SaveResult SaveChanges(JObject saveBundle)
{
return _contextProvider.SaveChanges(saveBundle);
}
}
Angular Service Like This :
var services = function (http) {
breeze.config.initializeAdapterInstance("modelLibrary", "backingStore");
this.getBybreeze = function (successed) {
var dataService = new breeze.DataService({
serviceName: 'breeze/Zza',
hasServerMetadata: false
});
var manager = new breeze.EntityManager(
{
dataService: dataService
});
var entityQuery = breeze.EntityQuery;
return entityQuery.from('Customers').using(manager).execute().then(successed).catch();
}
this.saveByBreeze =function () {
var dataService = new breeze.DataService({
serviceName: 'breeze/Zza',
hasServerMetadata: false
});
var manager = new breeze.EntityManager(
{
dataService: dataService
});
manager.saveChanges().fail(function (error) { alert("Failed save to server: " + error.message); });
}
}
services.$inject = ["$http"];
app.service("TestService", services);
And Angular Controler Like This :
var controller = function (scope, testService, ngTableParams, filter, upload, notification) {
var self = this;
self.title = "Test";
self.customers = [];
self.selected = "";
self.selectedFirstName="";
self.selectedLastName="";
testService.getBybreeze(function (data) {
self.customers = data.results;
});
self.selectedCustomer = function () {
angular.forEach(self.customers, function (item) {
if (item.Id === self.selected) {
self.selectedFirstName = item.FirstName;
self.selectedLastName = item.LastName;
}
});
}
self.save = function () {
testService.saveByBreeze();
}
}
controller.$inject = ["$scope", "TestService", "NgTableParams", "$filter", "Upload", "Notification"];
app.controller("TestController", controller)
View :
<div class="col-md-12" style="margin-top:20px">
<div class="col-md-2 " style="margin-top: 7px">
<label class="">
Customers:
</label>
</div>
<div class="col-md-10">
<div class="col-md-3">
<select class=" form-control" ng-change="self.selectedCustomer()" name="Id" ng-model="self.selected" ng-options="item.Id as item.FullName for item in self.customers"></select>
</div>
</div>
<div class="col-md-10 form-group">
<hr style="border-color: #000080" />
<fieldset data-bind="with: currentCustomer">
<legend>Customer:</legend>
<label for="customerName">Name:</label>
<br/>
<input class="form-control" id="customerName" value="{{self.selectedFirstName}}" />
<label for="customerPhone">Tell:</label>
<br/>
<input id="customerPhone" class="form-control" value="{{self.selectedLastName}}" />
<br />
<button class=" btn btn-default" id="saveButton" ng-click="self.save()">Save</button>
</fieldset>
</div>
</div>
I think EveryThing Is ok
but when I save it,nothing Saved
Your code creates a new empty EntityManager with each query and save operation. Instead, you should create a single EntityManager in your TestService, and use it for all query and save operations.
var services = function (http) {
breeze.config.initializeAdapterInstance("modelLibrary", "backingStore");
var dataService = new breeze.DataService({
serviceName: 'breeze/Zza',
hasServerMetadata: false
});
var manager = new breeze.EntityManager(
{
dataService: dataService
});
this.getBybreeze = function (successed) {
var entityQuery = breeze.EntityQuery;
return entityQuery.from('Customers').using(manager).execute().then(successed);
}
this.saveByBreeze = function () {
manager.saveChanges().catch(function (error) { alert("Failed save to server: " + error.message); });
}
}
services.$inject = ["$http"];
app.service("TestService", services);

Argument '*' is not a function on AngularJS

Adding ng-controller on view causing Error: [ng:areq] Argument 'ValidationCtrl' is not a function, got undefined. Following are the code snippets:
profile.html
<div class="row" ng-controller="ValidationCtrl">
<div class="col-md-6">
<div class="form-group">
<label class="control-label">First Name</label>
<input type="text" placeholder="Enter your first name" class="form-control" name="firstname" ng-model="user.first_name">
<span class="error text-small block" ng-if="Form.first_name.$dirty && Form.first_name.$invalid">Last Name is required</span>
<span class="success text-small" ng-if="Form.first_name.$valid">Wonderful!</span>
</div>
</div>
</div>
app.js
var myApp = angular.module("MyApp",['ngResource','ngRoute','ui.router','ngMessages','ngResource','cfp.loadingBar','duScroll','ngAnimate','satellizer','pascalprecht.translate','ngCookies','oc.lazyLoad','ui.bootstrap','toastr'])
.config(['$stateProvider', '$urlRouterProvider','$authProvider','$ocLazyLoadProvider','JS_REQUIRES',function($stateProvider, $urlRouterProvider,$authProvider,$ocLazyLoadProvider,jsRequires){
$stateProvider
.state('app.profile', {
url: '/profile',
templateUrl: "views/profile.html",
title: 'Buttons',
resolve: loadSequence('flow','validationCtrl')
});
$ocLazyLoadProvider.config({
debug: false,
events: true,
modules: jsRequires.modules
});
function loadSequence() {
var _args = arguments;
return {
deps: ['$ocLazyLoad', '$q',
function ($ocLL, $q) {
var promise = $q.when(1);
for (var i = 0, len = _args.length; i < len; i++) {
promise = promiseThen(_args[i]);
}
return promise;
function promiseThen(_arg) {
if (typeof _arg == 'function')
return promise.then(_arg);
else
return promise.then(function () {
var nowLoad = requiredData(_arg);
if (!nowLoad)
return $.error('Route resolve: Bad resource name [' + _arg + ']');
return $ocLL.load(nowLoad);
});
}
function requiredData(name) {
if (jsRequires.modules)
for (var m in jsRequires.modules)
if (jsRequires.modules[m].name && jsRequires.modules[m].name === name)
return jsRequires.modules[m];
return jsRequires.scripts && jsRequires.scripts[name];
}
}]
};
}
}]);
validationCtrl.js
'use strict';
/**
* controller for Validation Form example
*/
myApp.controller('ValidationCtrl', ["$scope", "$state", "$timeout", "SweetAlert", function ($scope, $state, $timeout, SweetAlert) {
alert('validation');
$scope.master = $scope.myModel;
$scope.form = {
submit: function (form) {
var firstError = null;
if (form.$invalid) {
var field = null, firstError = null;
for (field in form) {
if (field[0] != '$') {
if (firstError === null && !form[field].$valid) {
firstError = form[field].$name;
}
if (form[field].$pristine) {
form[field].$dirty = true;
}
}
}
angular.element('.ng-invalid[name=' + firstError + ']').focus();
SweetAlert.swal("The form cannot be submitted because it contains validation errors!", "Errors are marked with a red, dashed border!", "error");
return;
} else {
SweetAlert.swal("Good job!", "Your form is ready to be submitted!", "success");
//your code for submit
}
},
reset: function (form) {
$scope.myModel = angular.copy($scope.master);
form.$setPristine(true);
}
};
}]);
and my config.constant.js
myApp.constant('JS_REQUIRES', {
scripts: {
'validationCtrl': ['controllers/validationCtrl.js']
}});
Thanks!

Categories