I am very new to front-end development and I thought it would be cool to add drag and drop to a current upload page. However after starting to hook everything up with ng-flow (a directive that assists with drag and drop) I cannot seem to make the connection on how to add the files to the file list. If you think I don't even need the directive and am just overkilling this and there is a simpler solution I would be willing to make changes as well. NOTE: I am giving only samples of the code so dont ding it for not compiling!
fileModelDirective:
app.directive('fileModel', ['$parse', '$log', '$confirm',
function ($parse, $log, $confirm) {
return {
restrict: 'A',
link: function (scope, element, attrs) {
var model = $parse(attrs.fileModel);
var modelSetter = model.assign;
scope.sampleFile = model;
element.bind('change', function () {
// if the file open dialog is raised and the file name
// is cleared and cancel is pressed then a reset is needed
// document.getElementById('file-upload-name').innerHTML = "";
// document.getElementById('file-upload-btn').disabled = true;
// status always needs reset if choosing another file
scope.$apply(function () {
modelSetter(scope, element[0].files);
if (document.getElementById('file-upload').files) {
// This iterates over to see if the total files size is greater than 100MB
const maxFilesSize = 104857600;
var totalFilesSize = 0;
var numberOfDataSamples = element[0].files.length;
}
});
});
} // link
};
}]); // fileModel
fileMethod
$scope.uploadFile = function () {
console.log(flow)
var file = flow.file;
$scope.numberOfFiles = document.getElementById('file-upload').files.length;
$scope.filesTotalSize = 0;
for (var i = 0; i < document.getElementById('file-upload').files.length; i++) {
$scope.filesTotalSize = document.getElementById('file-upload').files[i].size + $scope.filesTotalSize;
}
fileUpload Service
app.service('fileUpload', ['$http', '$log',
function ($http, $log) {
this.uploadFileToUrl = function (file, uploadUrl) {
//$log.debug("file(s)");
//$log.debug(file);
var fd = new FormData();
angular.forEach(file, function (value, key) {
fd.append(key, value);
});
return $http.post(uploadUrl, fd, {
transformRequest: angular.identity,
headers: {
'Content-Type': undefined,
'enctype': "multipart/form-data"
}
})
}; // uploadFileToUrl
}]); // fileUpload
html
<div flow-init flow-files-submitted="$flow.upload()" class="ng-scope">
<div flow-drop>
<span for="file-upload"
class="btn btn-primary" flow-btn style="margin-top: 10px; ">Upload File
<input id="file-upload" type="file" multiple="multiple" file-model="sampleFile"
style="visibility: hidden; position: absolute;"></span>
<p flow-prevent-drop
flow-drag-enter="style={border: '5px dashed purple'}"
flow-drag-leave="style={}"
ng-style="style"
style="margin-top: 10px;width: 100%;min-height: 50px;">
Drag And Drop your file here</p>
<br>
<span ng-repeat="file in $flow.files track by $index">
{{file.name + ", " }}
</span>
<div style="margin-left: 2px; margin-top: 10px;">
<button id="file-upload-btn" class="btn btn-primary"
ng-click="showMask(); uploadFile();">
Upload
</button>
<button class="btn btn-primary" style="float: right;"
ng-click="navigateTo('/startup')">
Cancel
</button>
<button style="float: right; margin-right: 6px;" class="btn btn-primary"
ng-click="$flow.cancel()">
Clear
</button>
</div>
</div>
</div>
I'm just experimenting with a similar service. Taking angular Array of files, and pushing the items onto the javascript "file-upload".FileList array, but no luck, as the 'files' property is a readonly FileList object.
A pre-packaged solution:
http://blueimp.github.io/jQuery-File-Upload/angularjs.html
and it has drag and drop on to the whole page working.
This one: http://angular-file-upload.appspot.com/ even has Paste and access to Camera on mobile.
Your solution for adding files to the formData is good and inline with jquery ajaxSubmit form code
Maybe you could create a Plnk to collaborate on ...
formdata.append(a[i].name, a[i].value);
Related
In multiple image upload how to delete particular image if i click that image in angularjs.i have uploaded multiple image and i have textbox with every uploaded image.if i click image delete icon it removes the image with that textbox.my view code looks below
<input type="file" multiple file-upload /> {{files.length}}
<div ng-repeat="step in files">
<img ng-src="{{step.src}}" />
<input type="text" ng-model="comment[$index]"><br>
<input type="button" onclick="removeImage($index)" value="delete">
</div>
In my angular controller code looks like below
app.directive('fileUpload', function() {
return {
scope: true, //create a new scope
link: function(scope, el, attrs) {
el.bind('change', function(event) {
var files = event.target.files;
//iterate files since 'multiple' may be specified on the element
for (var i = 0; i < files.length; i++) {
//emit event upward
scope.$emit("fileSelected", {
file: files[i]
});
}
});
}
};
});
$scope.files = [];
$scope.$on("fileSelected", function(event, args) {
var item = args;
$scope.files.push(item);
var reader = new FileReader();
reader.addEventListener("load", function() {
$scope.$apply(function() {
item.src = reader.result;
});
}, false);
if (item.file) {
reader.readAsDataURL(item.file);
}
});
Instead of onclick use ng-click and use javascript splice function to remove an item from an array
<input type="button" ng-click="removeImage($index)" value="delete">
$scope.removeImage = function(index){
$scope.files.splice(index,1)
}
I have this problem in my app, when I use slice to remove the user from the list. However, it does not remove from the list. I am getting the user with a API url call. But for some reason, it does not remove the user from the list. Please, have a look at my code. If, you guys want the full code, I have put it in my github. I hope we both can solve this. Thank you in advance.
Here is my code:
<div ng-controller="MyCtrl">
<div ng-repeat="person in userInfo.lawyers | filter : {id: lawyerId}">
<a class="back" href="#/lawyer">Back</a>
<button type="button" class="edit" ng-show="inactive" ng-click="inactive = !inactive">
Edit
</button>
<button type="submit" class="submit" ng-show="!inactive" ng-click="inactive = !inactive">Save</button>
<a class="delete" ng-click="confirmClick(); confirmedAction(person);" confirm-click>Confirm</a>
<div class="people-view">
<h2 class="name">{{person.firstName}}</h2>
<h2 class="name">{{person.lastName}}</h2>
<span class="title">{{person.email}}</span>
<span class="date">{{person.website}} </span>
</div>
<div class="list-view">
<form>
<fieldset ng-disabled="inactive">
<legend>Basic Info</legend>
<b>First Name:</b>
<input type="text" ng-model="person.firstName">
<br>
<b>Last Name:</b>
<input type="text" ng-model="person.lastName">
<br>
<b>Email:</b>
<input type="email" ng-model="person.email">
<br>
<b>Website:</b>
<input type="text" ng-model="person.website">
<br>
</fieldset>
</form>
</div>
</div>
</div>
App.js
var app = angular.module("Portal", ['ngRoute', 'ui.bootstrap' ]);
app.controller('MyCtrl', function($scope, $window) {
$scope.inactive = true;
$scope.confirmedAction = function (lawyer) {
$scope.$apply(function () {
var index = $scope.userInfo.lawyers.indexOf(lawyer);
console.log($scope.userInfo.lawyers);
$scope.userInfo.lawyers.splice(index, 1);
console.log($scope.userInfo.lawyers);
$window.location.href = '#/lawyer';
});
};
});
app.directive('confirmClick', ['$q', 'dialogModal', function($q, dialogModal) {
return {
link: function (scope, element, attrs) {
// ngClick won't wait for our modal confirmation window to resolve,
// so we will grab the other values in the ngClick attribute, which
// will continue after the modal resolves.
// modify the confirmClick() action so we don't perform it again
// looks for either confirmClick() or confirmClick('are you sure?')
var ngClick = attrs.ngClick.replace('confirmClick()', 'true')
.replace('confirmClick(', 'confirmClick(true,');
// setup a confirmation action on the scope
scope.confirmClick = function(msg) {
// if the msg was set to true, then return it (this is a workaround to make our dialog work)
if (msg===true) {
return true;
}
// msg can be passed directly to confirmClick('Are you sure you want to confirm?')
// in ng-click
// or through the confirm-click attribute on the
// <a confirm-click="Are you sure you want to confirm?"></a>
msg = msg || attrs.confirmClick || 'Are you sure you want to confirm?';
// open a dialog modal, and then continue ngClick actions if it's confirmed
dialogModal(msg).result.then(function() {
scope.$eval(ngClick);
});
// return false to stop the current ng-click flow and wait for our modal answer
return false;
};
}
}
}])
/*
Modal confirmation dialog window with the UI Bootstrap Modal service.
This is a basic modal that can display a message with yes or no buttons.
It returns a promise that is resolved or rejected based on yes/no clicks.
The following settings can be passed:
message the message to pass to the modal body
title (optional) title for modal window
okButton text for YES button. set false to not include button
cancelButton text for NO button. ste false to not include button
*/
.service('dialogModal', ['$modal', function($modal) {
return function (message, title, okButton, cancelButton) {
// setup default values for buttons
// if a button value is set to false, then that button won't be included
cancelButton = cancelButton===false ? false : (cancelButton || 'No');
okButton = okButton ===false ? false : (okButton || 'Yes');
// setup the Controller to watch the click
var ModalInstanceCtrl = function ($scope, $modalInstance, settings) {
// add settings to scope
angular.extend($scope, settings);
// yes button clicked
$scope.ok = function () {
// alert("Lawyer is confirmed");
$modalInstance.close(true);
};
// no button clicked
$scope.cancel = function () {
$modalInstance.dismiss('cancel');
};
};
// open modal and return the instance (which will resolve the promise on ok/cancel clicks)
var modalInstance = $modal.open({
template: '<div class="dialog-modal"> \
<div class="modal-header" ng-show="modalTitle"> \
<h3 class="modal-title">{{modalTitle}}</h3> \
</div> \
<div class="modal-body">{{modalBody}}</div> \
<div class="modal-footer"> \
<button class="btn btn-primary" ng-click="ok()" ng-show="okButton">{{okButton}}</button> \
<button class="btn btn-warning" ng-click="cancel()" ng-show="cancelButton">{{cancelButton}}</button> \
</div> \
</div>',
controller: ModalInstanceCtrl,
resolve: {
settings: function() {
return {
modalTitle: title,
modalBody: message,
okButton: okButton,
cancelButton: cancelButton
};
}
}
});
// return the modal instance
return modalInstance;
}
}])
app.config(function ($routeProvider) {
$routeProvider
.when("/lawyer", {
controller: "HomeController",
templateUrl: "partials/home.html"
})
.when("/lawyer/:id", {
controller: "LawyerController",
templateUrl: "partials/about.html"
})
.otherwise({
redirectTo: '/lawyer'
});
});
But the element is getting deleted from list right?
If yes then, Try this :
$scope.confirmedAction = function (lawyer) {
$scope.$apply(function () {
var index = $scope.userInfo.lawyers.indexOf(lawyer);
console.log($scope.userInfo.lawyers);
$scope.userInfo.lawyers.splice(index, 1);
console.log($scope.userInfo.lawyers);
$window.location.href = '#/lawyer';
});
});
Or
$scope.confirmedAction = function (lawyer) {
$timeout(function () {
var index = $scope.userInfo.lawyers.indexOf(lawyer);
console.log($scope.userInfo.lawyers);
$scope.userInfo.lawyers.splice(index, 1);
console.log($scope.userInfo.lawyers);
$state.go($state.current, {}, {reload: true});
// $window.location.href = '#/lawyer';
},1100);
});
The problem is that you don't get the index from IndexOf when you using it on an array of objects like you do. Read more about the IndexOf here.
Instead, use map and then use IndexOf on that
Try it like this:
$scope.confirmedAction = function (lawyer) {
var index = $scope.userInfo.lawyers.map(function(e) { return e.id; }).indexOf(lawyer.id);
$scope.userInfo.lawyers.splice(index, 1);
console.log($scope.userInfo.lawyers);
$window.location.href = '#/lawyer';
};
And also, the controller changes will by default be detected by the digest loop of angular so no need to use $scope.$apply.
Also, simplifyed your plunker with the basic get array list and remove function. Use that to build your way forvered
https://plnkr.co/edit/w6NuVLcqzc5Rjs7L6Cox?p=preview
Is it possible to convert file object to image object?
I need width and height from file (which is an image), here is my code:
view:
<button id="image_file" class="md-button md-raised md-primary"
type="file" ngf-select="uploadFile($file)">
SELECT FILE
</button>
<md-input-container>
<div class="raised">
<input id="image_file_name" type="text" ng-model="vm.file.name"></input>
</div>
</md-input-container>
controller:
app.controller('imageController', function($scope, fileService) {
$scope.vm = {};
$('.intro').show(1000);
$scope.uploadFile = function(file) {
$scope.vm.file = "";
$scope.vm.file = file; //<---- for example here, how it should be done?
fileService.uploadFile($scope);
}
service:
angular.module('app')
.service('fileService', function ($http, validationService) {
this.uploadFile = function ($scope){
if (validationService.isFileValidate($scope)) {
$scope.vm.acceptableFormat = true;
} else {
$scope.vm.acceptableFormat = false;
}
};
});
The library already seems to give most of what you require. To read width and height properties of the file/image .
//Add accept option to filter only images
<button id="image_file" class="md-button md-raised md-primary"
type="file" accept="image/*" ngf-select="uploadFile($file)">
SELECT FILE
</button>
Controller
$scope.uploadFile = function(file) {
$scope.vm.file = "";
$scope.vm.file = file;
// show all file properties
console.log(file); // Show available properties
console.log(file.$ngfWidth +','+ file.$ngfHeight) // Your width and height
fileService.uploadFile($scope);
}
You should probably check out it's Features.
I have a page employee.html with a list of dependents and for each row (li) an inner button with the directive ng-click="editDependent({{dependent.id}})". That button tries to call a modal box.
The employee.html is loaded in a ui_view div from an index.html
I saw that each button in view source with chrome are correctly bound ng-click="editDepedent(1)" and so on.
But at the same time I have an error
angular.min.js:118 Error: [$parse:syntax] http://errors.angularjs.org/1.5.8/$parse/syntax?p0=%7B&p1=invalid%20key&p2=11&p3=editDependent(%7B%7Bdependent.id%7D%7D)&p4=%7Bdependent.id%7D%7D)
I'm trying to pass my dependent id to my modal and the previous scope also that contains the info about the employee. So how can I achieve this parameter passing?
This is my main controller
app.controller('EmployeeController', function ($scope, $stateParams, $uibModal, EmployeeService) {
if($stateParams.id){
EmployeeService.getEmployee($stateParams.id).then(function(employee){
$scope.employee = employee;
EmployeeService.setCurrentEmployee(employee);
});
}
$scope.editDependent = function(id){
if(id){
$scope.dependentid = id;
}
var uibModalInstance = $uibModal.open({
templateUrl : 'modal_dependent.html',
controller : 'DependentController',
scope: $scope
});
return uibModalInstance;
}
});
This is my dependent controller to catch the value
app.controller('DependentController', function($scope, $uibModal, $uibModalInstance, $stateParams, EmployeeService){
//Following line does not work because it gets the ID of employee which is passed by querystring
//var dependentID = $stateParams.id;
if($scope.dependentid){
var currentEmployee = EmployeeService.getCurrentEmployee();
//find the current dependent
for(var i = 0; i < currentEmployee.dependents.length; i++){
//*****************************************************
//Hardcoding 1 to test the dependent number 1 but it should be the dependent id parameter
if(currentEmployee.dependents[i].id == 1){
$scope.dependent = currentEmployee.dependents[i];
break;
}
}
}else{
$scope.dependent = { id : 0 };
}
$scope.editableDependent = angular.copy($scope.dependent);
//Submit button in modal
$scope.submitDependent = function(){
DependentService.saveDependent($scope.editableDependent);
$scope.dependent = angular.copy($scope.editableDependent);
$uibModalInstance.close();
}
});
UPDATE
employee.html
<form name="employee_form">
<div>
<h1> {{employee.name}} </h1>
<h3>Dependents</h3>
<button class="btn bgcolor-rb-main" x-ng-click="editDependent(0)">
Add new
</button>
<ul class="list-inline">
<li x-ng-repeat="dependent in employee.dependents">
<button x-ng-click="editDependent({{dependent.id}})">
Edit
</button><br>
<div>{{dependent.name}}</div>
</li>
</ul>
</div>
</form>
This is my modal_dependent.html
<div class="modal-header">
<h4>Dependent</h4>
</div>
<div class="modal-body">
<div class="form-group">
<input type="text" id="txtName" x-ng-model="editableDependent.name" />
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" x-ng-click="discardChanges()">Discard</button>
<button type="submit" class="btn btn-primary" x-ng-click="submitDependent()">Save</button>
</div>
UPDATE
I changed my controller to initialize before $scope.dependent
app.controller('DependentController', function($scope, $uibModal, $uibModalInstance, $stateParams, EmployeeService){
//Following line does not work because it gets the ID of employee which is passed by querystring
//var dependentID = $stateParams.id;
$scope.dependent = { id : 0 };
if($scope.dependentid){
var currentEmployee = EmployeeService.getCurrentEmployee();
//find the current dependent
for(var i = 0; i < currentEmployee.dependents.length; i++){
//*****************************************************
//Hardcoding 1 to test the dependent number 1 but it should be the dependent id parameter
if(currentEmployee.dependents[i].id == 1){
$scope.dependent = currentEmployee.dependents[i];
break;
}
}
}
$scope.editableDependent = angular.copy($scope.dependent);
//Submit button in modal
$scope.submitDependent = function(){
DependentService.saveDependent($scope.editableDependent);
$scope.dependent = angular.copy($scope.editableDependent);
$uibModalInstance.close();
}
});
SOLVED
My button changed from this
<button x-ng-click="editDependent({{dependent.id}})">Edit</button>
To this
<button x-ng-click="editDependent(dependent.id)">Edit</button>
i think there is parsing error you have to define
$scope.dependentid = {};
before using it,
or otherwise you can use it as a model (if you are submitting a form on frontend like this)
<input type="hidden" ng-model="dependentid" />
it will be better to understand for me if you edit the code and add some frontend html
I'm looking for a way in angular to tab through hidden inputs. So I have multiple input forms but when not on focus I want them to just display the text. I'm looking for the ability to once I've selected an input to tab through the other inputs even though they are currently hidden.
Any suggestions?
Use Angular directives to make your inputs into inline editors. When the page loads you'll be in display mode (i.e. the display div will be shown and the editor div will be hidden), then on clicking, the mode switches to Edit mode and the visibility is reversed.
Here's a quick snippet of what a DatePicker control would look like when wrapped in such a directive. Using Angular 1 and Bootstrap 3 (follows John Papa's Angular Style Guide):
HTML Template (inlineDatePicker.html):
<div class="inline-edit">
<div ng-if="!vm.inEditMode" data-ng-click="vm.enableEditMode()">
<input type="hidden" data-ng-model="vm.dateModel" data-ng-required="vm.dateRequired" /><span>{{vm.dateModel}}</span> <span class="glyphicon glyphicon-calendar"></span>
</div>
<div ng-if="vm.inEditMode">
<div class="well well-sm" style="position: absolute; z-index: 10">
<datepicker data-ng-model="vm.dateModel" data-show-weeks="false"></datepicker>
<button type="button" class="btn btn-sm btn-info" ng-click="vm.today()">Today</button>
<button type="button" class="btn btn-sm btn-danger" ng-click="vm.cancel()">Cancel</button>
</div>
</div>
</div>
And the underlying directive (inlineDatePicker.directive.js):
(function () {
'use strict';
angular.module('myApp.inlineEdit')
.directive('inlineDatePicker', inlineDatePicker);
function inlineDatePicker() {
'use strict';
inlineDatePickerController.$inject = ['$scope', '$timeout'];
return {
restrict: 'A',
replace: true,
transclude: false,
templateUrl: '/App/inlineEdit/date/inlineDatePicker.html',
scope: {
dateModel: '=',
dateRequired: '#',
dateChanged: '&'
},
controller: inlineDatePickerController,
controllerAs: 'vm',
};
function inlineDatePickerController($scope, $timeout) {
/* jshint validthis:true */
var vm = this;
vm.inEditMode = false;
vm.dateModel = $scope.dateModel;
vm.dateRequired = $scope.$eval($scope.dateRequired);
vm.enableEditMode = enableEditMode;
vm.cancel = cancel;
vm.today = today;
function enableEditMode() {
vm.inEditMode = true;
}
function cancel() {
vm.inEditMode = false;
}
function today() {
vm.dateModel = new Date();
}
$scope.$watch('vm.dateModel', function (curr, orig) {
$scope.dateModel = vm.dateModel;
if (curr != orig && vm.inEditMode) {
$timeout($scope.dateChanged, 0);
}
vm.inEditMode = false;
});
$scope.$watch('dateModel', function () {
vm.dateModel = $scope.dateModel;
});
}
}
})();