verify email is already used or not angularjs - angularjs

I start with angularJS and I want to check if the email entered in the form already exists or not . for that, I will use RESTto communicate withe back_end.My problem is : how to check email before sending the form with a directive and display an error message if the email is already used.
<form name="registrationForm">
<div>
<label>Email</label>
<input type="email" name="email" class="form-group"
ng-model="registration.user.email"
ng-pattern="/^[_a-z0-9]+(\.[_a-z0-9]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,8})$/"
required compare-to="registration.user.email"
/>
the model
demoApp.directive('existTo', [function () {
return {
require: "ngModel",
scope: {
otherModelValue: "=existTo"
},
link: function(scope, element, attributes, ngModel) {
ngModel.$validators.existTo = function(modelValue) {
return modelValue == scope.otherModelValue;
};
scope.$watch("otherModelValue", function() {
ngModel.$validate();
});
}
}; }]);
back_end checkmail: the controller
demoApp.controller('signupCtrl',function($scope,$http) {
$scope.verficationEmail = function(mail) {
$scope.test = mail;
var urll="";
var test="";
$scope.urll="http://localhost:8080/app/personne/verifmail?msg=";
$scope.aplrest=$scope.urll+$scope.test;
var ch3=$scope.aplrest;
$http.post(ch3).
success(function(respons) {
$scope.data = respons;
$scope.valid = respons.valid;
if ( $scope.valid == "false") {
$scope.msgalert="mail used";
}
})
};});
thank you in advance for your assistance

You will most likely want to put the verficiation function in a service and inject it wherever it's needed:
demoApp.factory('verifyEmail', function() {
return function(mail) {
var test=mail;
var urll="http://localhost:8080/app/personne/verifmail?msg=";
var aplrest=urll+test;
var ch3=aplrest;
return $http.post(ch3)
};
});
Then...
In your directive:
demoApp.directive('existTo', ["$q","verifyEmail",function ($q, verifyEmail) {
return {
require: "ngModel",
scope: {
// This is probably not needed as ngModel's
// validators will pass the current value anyway
otherModelValue: "=existTo"
},
link: function(scope, element, attributes, ngModel) {
// Note the change to $asyncValidators here <-------------
ngModel.$asyncValidators.existTo = function(modelValue) {
var deferred = $q.defer()
verifyEmail(modelValue).then(function(respons){
deferred.resolve(respons.valid);
});
return deferred.promise
};
scope.$watch("otherModelValue", function() {
ngModel.$validate();
});
}
}; }]);
In your controller:
demoApp.controller('signupCtrl',function($scope,$http,verifyEmail) {
$scope.verficationEmail = function (mail) {
verifyEmail(mail).success(function(respons) {
$scope.data = respons;
$scope.valid = respons.valid;
if ( $scope.valid == "false") {
$scope.msgalert="mail used";
}
});
}
});
Also, in your html you dont seem to be actually using the directive exist-to, I'm guessing that's what compare-to should have been. But, in any case, it might look like this:
<input type="email" name="email" class="form-group"
ng-model="registration.user.email"
ng-pattern="/^[_a-z0-9]+(\.[_a-z0-9]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,8})$/"
required exist-to
/>
Note that there's no need to pass the model value to the directive
Hope that helps.

Related

Angular async validation with multiple form fields

I have a async validation directive which works fine when, but it depends on two fields to define if a person exists (numId and type), here's the code:
app.directive('personaUnica', function($http, $q){
return{
require:'ngModel',
scope: {
tipo: "=personaUnica"
},
link: function(scope, element, attrs, ctrl){
ctrl.$asyncValidators.personaUnica = function(modelValue, viewValue){
if (ctrl.$isEmpty(modelValue)) {
// valido si es vacio
return $q.when();
}
var defer = $q.defer();
$http.get('/someRESTEndpoint/', {
params:{ identificacion: modelValue, tipo: scope.tipo }
}).then(function(respuesta){
//Person found, not valid
if( respuesta.data.elementoExiste ){
defer.reject('Persona existe.');
}
}, function(respuesta){
//Person not found, resolve promise
if(!respuesta.data.elementoExiste){
defer.resolve();
}
});
return defer.promise;
}
}
}
});
But I dont know how to make the same validation when the other dependant field has changed.
I've read something about require ^form in the directive but in kinda lost.
I've tried to add this block of code
scope.$watch('tipo', function(){
ctrl.$validate();
});
But then I get an infinite $digest loop.
Thanks in advance.
You can do something like this:
$scope.$watch('tipo', function(newValue, oldValue, scope) {
if (newValue != oldValue) {
ctrl.$validate();
}
});
This way, $scope.watch will be called everytime you have a new value on your $scope.tipo.
Turns out that I was using watch in the wrong place inside the ctrl.$asyncValidators.numId, it has to be outside. Now It works as expected.
app.directive('numId', function($http, $q){
return {
restrict : 'A',
scope: {
tipo: "=numId"
},
require: 'ngModel',
link: function(scope, element, attrs, ctrl){
ctrl.$asyncValidators.numId = function(modelValue, viewValue){
if (ctrl.$isEmpty(modelValue) || ctrl.$isEmpty(scope.tipo)) {
// consider empty model valid
console.log('Not going yet..');
return $q.when();
}
var defer = $q.defer();
$http.get("/some-server/endpoint",{
params:{ identificacion: modelValue, tipo: scope.tipo }
}).then(function(res){
if( res.data.personaExiste){
console.log('exists, not valid')
defer.reject('exists, not valid');
}else if( !res.data.personaExiste ){
console.log('NOT exists, valid!')
defer.resolve();
}
}, function(){
defer.reject('Error...');
});
return defer.promise;
}
// Search when tipo is changed
scope.$watch('tipo', function(){
console.log('Tipo:' + scope.tipo)
ctrl.$validate();
});
}
}
});
And the html:
<div class="form-group">
<label>Numero identificacion</label>
<input type="text"
name="numId"
required
ng-model="busqueda.numId"
num-id="busqueda.tipoUsuario">
<pre class="well"> {{ frmBuscar.numId.$error }} </pre>
</div>

Predefine error message with angular validation custom directive

I am doing angular validation as follows:
<form name="form" ng-submit="vm.create(vm.job)" validation="vm.errors">
<input name="vm.job.position" type="text" ng-model="vm.job.position" validator />
When the form is submitted the directive gets the name of the property, e.g. position, from the ng-model. It then checks if vm.errors has a message for that property. If yes then adds a span with the error message after the input.
However, I would also like to use the same directive in another way:
<form name="form" ng-submit="vm.create(vm.job)" validation="vm.errors">
<input name="vm.job.position" type="text" ng-model="vm.job.position" />
<span class="error" validator="position"></span>
In this case I removed the validator from the input and added the span already allowing me to control where the error will be displayed. In this case I am using validator="position" to define to which model property the error message is associated.
I am not sure how should I add this functionality to my current code ... Any help is appreciated.
The following is all the code I have on my directives:
(function () {
"use strict";
angular.module("app").directive("validation", validation);
function validation() {
var validation = {
controller: ["$scope", controller],
replace: false,
restrict: "A",
scope: {
validation: "="
}
};
return validation;
function controller($scope) {
var vm = this;
$scope.$watch(function () {
return $scope.validation;
}, function () {
vm.errors = $scope.validation;
})
}
}
angular.module("app").directive("validator", validator);
function validator() {
var validator = {
link: link,
replace: false,
require: "^validation",
restrict: "A"
};
return validator;
function link(scope, element, attributes, controller) {
scope.$watch(function () {
return controller.errors;
}, function () {
if (controller.errors) {
var result = controller.errors.filter(function (error) {
if (error.flag == null)
return false;
var position = attributes.name.lastIndexOf(".");
if (position > -1)
return attributes.name.slice(position + 1).toLowerCase() === error.flag.toLowerCase();
else
return attributes.name.toLowerCase() === error.flag.toLowerCase();
});
if (result.length > 0) {
var error = element.siblings("span.error").first();
if (error.length == 0)
element.parent().append("<span class='error'>" + result[0].info + "</span>");
else
error.text(result[0].info);
} else {
element.siblings("span.error").first().remove();
}
}
}, true);
}
}
})();

directive angularjs to check mail used or not

i want to check if email is already used or not (communication with back-end) but the error message is not shown in the screen.
the verficiation function service :
demoApp.factory('verifyEmail', function($http) {
return function(mail) {
var test=mail;
var urll="http://localhost:8080/app/personne/verifmail?msg=";
var aplrest=urll+test;
var ch3=aplrest;
return $http.post(ch3)
};});
the directive (with the help of #jsonmurphy)
demoApp.directive('existTo', ["$q","verifyEmail",function ($q, verifyEmail) {
return {
require: "ngModel",
scope: {
otherModelValue: "=existTo"
},
link: function(scope, element, attributes, ngModel) {
// Note the change to $asyncValidators here <-------------
ngModel.$asyncValidators.existTo = function(modelValue) {
var deferred = $q.defer();
verifyEmail(modelValue).then(function(respons) {
// the respons can be {exist="true"} or{exist="false"}
var rep=respons.exist;
deferred.resolve(rep);
});
return deferred.promise;
};
scope.$watch("otherModelValue", function() {
ngModel.$validate();
});
}
}; }]);
the html file:
<label>Email</label>
<input type="email" name="email" class="form-group"
ng-model="registration.user.email"
ng-pattern="/^[_a-z0-9]+(\.[_a-z0-9]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,8})$/"
required exist-To="registration.user.email"/>
<span style="color:red" ng-show="registrationForm.email.$dirty && registrationForm.email.$invalid">
<span ng-show="registrationForm.email.$error.required">champs email obligatoire.</span>
<span ng-show="registrationForm.email.$error.pattern">Invalid email address.</span>
<span ng-show="registrationForm.email.$error.existTo">mail already exist.</span>
</span>
this the solution
demoApp.directive('existTo', ["$q","verifyEmail",function ($q, verifyEmail) {
return {
require: "ngModel",
scope: {
otherModelValue: "=existTo"
},
link: function(scope, element, attributes, ngModel) {
// Note the change to $asyncValidators here <-------------
ngModel.$asyncValidators.existTo = function(modelValue) {
var deferred = $q.defer();
// window.alert("l email a tester "+modelValue);
verifyEmail(modelValue).success(function(respons) {
// the respons can be {exist="true"} or{exist="false"}
// window.alert("la reponse " +respons);
var rep=respons.exist;
// window.alert("la reponse " +rep);
if (rep =="false") {
// The username is available
deferred.resolve();
} else {
deferred.reject();
}
});
return deferred.promise;
};
scope.$watch("otherModelValue", function() {
ngModel.$validate();
});
}
}; }]);

$asyncValidators with params for two modes ('new' and 'edit' form)

I'm using $asyncValidators to check if email is available or not.
I have only one controller and template for two modes : 'new' and 'edit'.
i created a directive for this check. But on 'edit' mode, i don't want to check current email. So, in my controller, i've created $scope.initialEmail to compare it with entered email. But i don't know how to use it in directive (for edit mode).
Template :
<input id="email" name="email" type="email" class="form-control"
placeholder="{{'placeholders_email'|i18n}}"
ng-model="user.email" ng-required="true" email-available/>
<ng-messages for="myForm.email.$error" ng-if="myForm.email.$dirty">
<ng-message class="red" when="emailAvailable">{{'email_exists_in_db'|i18n}}</ng-message>
...
Controller :
//formMode is injected in controller ('new' or 'edit')
$scope.formMode = angular.copy(formMode);
$scope.user = {email: '...', ...};
switch(formMode){
case 'edit':
$scope.initialEmail = angular.copy($scope.user.email);
break;
}
Factory :
//AuthHttp is an auth service using $http
angular.module('myapp').factory('EmailAvailableValidator', ['$q', 'AuthHttp', function($q, AuthHttp) {
return function(email) {
var deferred = $q.defer();
AuthHttp.get('/rest/users/emailAvailable/'+email).then(function() {
deferred.resolve();
}, function() {
deferred.reject();
});
return deferred.promise;
}}]);
Directive :
angular.module('myapp').directive('emailAvailable', ['EmailAvailableValidator', function(EmailAvailableValidator) {
return {
restrict: "A",
require : 'ngModel',
link : function(scope, element, attrs, ngModel) {
switch(scope.formMode){
case 'new':
ngModel.$asyncValidators.emailAvailable = EmailAvailableValidator;
break;
case 'edit':
ngModel.$asyncValidators.emailAvailable = function(email){ // ?
if(!_.isEqual(scope.initialEmail, ngModel.$modelValue)){ // ?
return EmailAvailableValidator; // ??
}
};
break;
}
}
}
}]);
The solution is to add $q.when for the edit mode like this :
Factory :
angular.module('myapp').factory('UsersService', ['AuthHttp', '$q', function (AuthHttp, $q) {
return {
emailAvailable: function(email){
var deferred = $q.defer();
AuthHttp.get('/rest/users/emailAvailable/'+email).then(function() {
deferred.resolve();
}, function() {
deferred.reject();
});
return deferred.promise;
}
}
}]);
Directive :
angular.module('myapp').directive('emailAvailable', ['UsersService', '$q', function(UsersService, $q) {
return {
restrict: "A",
require : 'ngModel',
link : function(scope, element, attrs, ngModel) {
switch(scope.formMode){
case 'new':
ngModel.$asyncValidators.emailAvailable = function(modelValue, viewValue) {
return UsersService.emailAvailable(modelValue || viewValue);
};
break;
case 'edit':
ngModel.$asyncValidators.emailAvailable = function(modelValue, viewValue){
var newValue = modelValue || viewValue;
var promise;
if(!_.isEqual(scope.initialEmail, newValue)){
promise = UsersService.emailAvailable(newValue);
} else {
promise = $q.when(!_.isEqual(scope.initialEmail, newValue));
}
return promise;
};
break;
}
}
}
}]);

ng-model for `<input type="file"/>` (with directive DEMO)

I tried to use ng-model on input tag with type file:
<input type="file" ng-model="vm.uploadme" />
But after selecting a file, in controller, $scope.vm.uploadme is still undefined.
How do I get the selected file in my controller?
I created a workaround with directive:
.directive("fileread", [function () {
return {
scope: {
fileread: "="
},
link: function (scope, element, attributes) {
element.bind("change", function (changeEvent) {
var reader = new FileReader();
reader.onload = function (loadEvent) {
scope.$apply(function () {
scope.fileread = loadEvent.target.result;
});
}
reader.readAsDataURL(changeEvent.target.files[0]);
});
}
}
}]);
And the input tag becomes:
<input type="file" fileread="vm.uploadme" />
Or if just the file definition is needed:
.directive("fileread", [function () {
return {
scope: {
fileread: "="
},
link: function (scope, element, attributes) {
element.bind("change", function (changeEvent) {
scope.$apply(function () {
scope.fileread = changeEvent.target.files[0];
// or all selected files:
// scope.fileread = changeEvent.target.files;
});
});
}
}
}]);
I use this directive:
angular.module('appFilereader', []).directive('appFilereader', function($q) {
var slice = Array.prototype.slice;
return {
restrict: 'A',
require: '?ngModel',
link: function(scope, element, attrs, ngModel) {
if (!ngModel) return;
ngModel.$render = function() {};
element.bind('change', function(e) {
var element = e.target;
$q.all(slice.call(element.files, 0).map(readFile))
.then(function(values) {
if (element.multiple) ngModel.$setViewValue(values);
else ngModel.$setViewValue(values.length ? values[0] : null);
});
function readFile(file) {
var deferred = $q.defer();
var reader = new FileReader();
reader.onload = function(e) {
deferred.resolve(e.target.result);
};
reader.onerror = function(e) {
deferred.reject(e);
};
reader.readAsDataURL(file);
return deferred.promise;
}
}); //change
} //link
}; //return
});
and invoke it like this:
<input type="file" ng-model="editItem._attachments_uri.image" accept="image/*" app-filereader />
The property (editItem.editItem._attachments_uri.image) will be populated with the contents of the file you select as a data-uri (!).
Please do note that this script will not upload anything. It will only populate your model with the contents of your file encoded ad a data-uri (base64).
Check out a working demo here:
http://plnkr.co/CMiHKv2BEidM9SShm9Vv
How to enable <input type="file"> to work with ng-model
Working Demo of Directive that Works with ng-model
The core ng-model directive does not work with <input type="file"> out of the box.
This custom directive enables ng-model and has the added benefit of enabling the ng-change, ng-required, and ng-form directives to work with <input type="file">.
angular.module("app",[]);
angular.module("app").directive("selectNgFiles", function() {
return {
require: "ngModel",
link: function postLink(scope,elem,attrs,ngModel) {
elem.on("change", function(e) {
var files = elem[0].files;
ngModel.$setViewValue(files);
})
}
}
});
<script src="//unpkg.com/angular/angular.js"></script>
<body ng-app="app">
<h1>AngularJS Input `type=file` Demo</h1>
<input type="file" select-ng-files ng-model="fileArray" multiple>
<code><table ng-show="fileArray.length">
<tr><td>Name</td><td>Date</td><td>Size</td><td>Type</td><tr>
<tr ng-repeat="file in fileArray">
<td>{{file.name}}</td>
<td>{{file.lastModified | date : 'MMMdd,yyyy'}}</td>
<td>{{file.size}}</td>
<td>{{file.type}}</td>
</tr>
</table></code>
</body>
This is an addendum to #endy-tjahjono's solution.
I ended up not being able to get the value of uploadme from the scope. Even though uploadme in the HTML was visibly updated by the directive, I could still not access its value by $scope.uploadme. I was able to set its value from the scope, though. Mysterious, right..?
As it turned out, a child scope was created by the directive, and the child scope had its own uploadme.
The solution was to use an object rather than a primitive to hold the value of uploadme.
In the controller I have:
$scope.uploadme = {};
$scope.uploadme.src = "";
and in the HTML:
<input type="file" fileread="uploadme.src"/>
<input type="text" ng-model="uploadme.src"/>
There are no changes to the directive.
Now, it all works like expected. I can grab the value of uploadme.src from my controller using $scope.uploadme.
I create a directive and registered on bower.
This lib will help you modeling input file, not only return file data but also file dataurl or base 64.
{
"lastModified": 1438583972000,
"lastModifiedDate": "2015-08-03T06:39:32.000Z",
"name": "gitignore_global.txt",
"size": 236,
"type": "text/plain",
"data": "data:text/plain;base64,DQojaWdub3JlIHRodW1ibmFpbHMgY3JlYXRlZCBieSB3aW5kb3dz…xoDQoqLmJhaw0KKi5jYWNoZQ0KKi5pbGsNCioubG9nDQoqLmRsbA0KKi5saWINCiouc2JyDQo="
}
https://github.com/mistralworks/ng-file-model/
This is a slightly modified version that lets you specify the name of the attribute in the scope, just as you would do with ng-model, usage:
<myUpload key="file"></myUpload>
Directive:
.directive('myUpload', function() {
return {
link: function postLink(scope, element, attrs) {
element.find("input").bind("change", function(changeEvent) {
var reader = new FileReader();
reader.onload = function(loadEvent) {
scope.$apply(function() {
scope[attrs.key] = loadEvent.target.result;
});
}
if (typeof(changeEvent.target.files[0]) === 'object') {
reader.readAsDataURL(changeEvent.target.files[0]);
};
});
},
controller: 'FileUploadCtrl',
template:
'<span class="btn btn-success fileinput-button">' +
'<i class="glyphicon glyphicon-plus"></i>' +
'<span>Replace Image</span>' +
'<input type="file" accept="image/*" name="files[]" multiple="">' +
'</span>',
restrict: 'E'
};
});
For multiple files input using lodash or underscore:
.directive("fileread", [function () {
return {
scope: {
fileread: "="
},
link: function (scope, element, attributes) {
element.bind("change", function (changeEvent) {
return _.map(changeEvent.target.files, function(file){
scope.fileread = [];
var reader = new FileReader();
reader.onload = function (loadEvent) {
scope.$apply(function () {
scope.fileread.push(loadEvent.target.result);
});
}
reader.readAsDataURL(file);
});
});
}
}
}]);
function filesModelDirective(){
return {
controller: function($parse, $element, $attrs, $scope){
var exp = $parse($attrs.filesModel);
$element.on('change', function(){
exp.assign($scope, this.files[0]);
$scope.$apply();
});
}
};
}
app.directive('filesModel', filesModelDirective);
I had to do same on multiple input, so i updated #Endy Tjahjono method.
It returns an array containing all readed files.
.directive("fileread", function () {
return {
scope: {
fileread: "="
},
link: function (scope, element, attributes) {
element.bind("change", function (changeEvent) {
var readers = [] ,
files = changeEvent.target.files ,
datas = [] ;
for ( var i = 0 ; i < files.length ; i++ ) {
readers[ i ] = new FileReader();
readers[ i ].onload = function (loadEvent) {
datas.push( loadEvent.target.result );
if ( datas.length === files.length ){
scope.$apply(function () {
scope.fileread = datas;
});
}
}
readers[ i ].readAsDataURL( files[i] );
}
});
}
}
});
I had to modify Endy's directive so that I can get Last Modified, lastModifiedDate, name, size, type, and data as well as be able to get an array of files. For those of you that needed these extra features, here you go.
UPDATE:
I found a bug where if you select the file(s) and then go to select again but cancel instead, the files are never deselected like it appears. So I updated my code to fix that.
.directive("fileread", function () {
return {
scope: {
fileread: "="
},
link: function (scope, element, attributes) {
element.bind("change", function (changeEvent) {
var readers = [] ,
files = changeEvent.target.files ,
datas = [] ;
if(!files.length){
scope.$apply(function () {
scope.fileread = [];
});
return;
}
for ( var i = 0 ; i < files.length ; i++ ) {
readers[ i ] = new FileReader();
readers[ i ].index = i;
readers[ i ].onload = function (loadEvent) {
var index = loadEvent.target.index;
datas.push({
lastModified: files[index].lastModified,
lastModifiedDate: files[index].lastModifiedDate,
name: files[index].name,
size: files[index].size,
type: files[index].type,
data: loadEvent.target.result
});
if ( datas.length === files.length ){
scope.$apply(function () {
scope.fileread = datas;
});
}
};
readers[ i ].readAsDataURL( files[i] );
}
});
}
}
});
If you want something a little more elegant/integrated, you can use a decorator to extend the input directive with support for type=file. The main caveat to keep in mind is that this method will not work in IE9 since IE9 didn't implement the File API. Using JavaScript to upload binary data regardless of type via XHR is simply not possible natively in IE9 or earlier (use of ActiveXObject to access the local filesystem doesn't count as using ActiveX is just asking for security troubles).
This exact method also requires AngularJS 1.4.x or later, but you may be able to adapt this to use $provide.decorator rather than angular.Module.decorator - I wrote this gist to demonstrate how to do it while conforming to John Papa's AngularJS style guide:
(function() {
'use strict';
/**
* #ngdoc input
* #name input[file]
*
* #description
* Adds very basic support for ngModel to `input[type=file]` fields.
*
* Requires AngularJS 1.4.x or later. Does not support Internet Explorer 9 - the browser's
* implementation of `HTMLInputElement` must have a `files` property for file inputs.
*
* #param {string} ngModel
* Assignable AngularJS expression to data-bind to. The data-bound object will be an instance
* of {#link https://developer.mozilla.org/en-US/docs/Web/API/FileList `FileList`}.
* #param {string=} name Property name of the form under which the control is published.
* #param {string=} ngChange
* AngularJS expression to be executed when input changes due to user interaction with the
* input element.
*/
angular
.module('yourModuleNameHere')
.decorator('inputDirective', myInputFileDecorator);
myInputFileDecorator.$inject = ['$delegate', '$browser', '$sniffer', '$filter', '$parse'];
function myInputFileDecorator($delegate, $browser, $sniffer, $filter, $parse) {
var inputDirective = $delegate[0],
preLink = inputDirective.link.pre;
inputDirective.link.pre = function (scope, element, attr, ctrl) {
if (ctrl[0]) {
if (angular.lowercase(attr.type) === 'file') {
fileInputType(
scope, element, attr, ctrl[0], $sniffer, $browser, $filter, $parse);
} else {
preLink.apply(this, arguments);
}
}
};
return $delegate;
}
function fileInputType(scope, element, attr, ctrl, $sniffer, $browser, $filter, $parse) {
element.on('change', function (ev) {
if (angular.isDefined(element[0].files)) {
ctrl.$setViewValue(element[0].files, ev && ev.type);
}
})
ctrl.$isEmpty = function (value) {
return !value || value.length === 0;
};
}
})();
Why wasn't this done in the first place? AngularJS support is intended to reach only as far back as IE9. If you disagree with this decision and think they should have just put this in anyway, then jump the wagon to Angular 2+ because better modern support is literally why Angular 2 exists.
The issue is (as was mentioned before) that without the file api
support doing this properly is unfeasible for the core given our
baseline being IE9 and polyfilling this stuff is out of the question
for core.
Additionally trying to handle this input in a way that is not
cross-browser compatible only makes it harder for 3rd party solutions,
which now have to fight/disable/workaround the core solution.
...
I'm going to close this just as we closed #1236. Angular 2 is being
build to support modern browsers and with that file support will
easily available.
Alternatively you could get the input and set the onchange function:
<input type="file" id="myFileInput" />
document.getElementById("myFileInput").onchange = function (event) {
console.log(event.target.files);
};
Try this,this is working for me in angular JS
let fileToUpload = `${documentLocation}/${documentType}.pdf`;
let absoluteFilePath = path.resolve(__dirname, fileToUpload);
console.log(`Uploading document ${absoluteFilePath}`);
element.all(by.css("input[type='file']")).sendKeys(absoluteFilePath);

Resources