How to trigger element click on angular js? - angularjs

I have an input file and it is hidden. I want to trigger the input file once the button is clicked but my code is not working. What changes does it need to make it work?
HTML:
<input type="file" ng-model="data.file" id="upload" style="display:none;">
<button type="button" ng-click="browseFile()">Choose a file</button>
JavaScript:
$scope.browseFile = function () {
angular.element(document.querySelector('#upload')).triggerHandler('click');
}

In html use something like below
<img id="preview_image" src="" accept="image/*" class="upload_img" alt="">
<input id="image_upload" ng-model="file" type="file" class="upload_image_file" />
And in controller use $watch
$scope.$watch("file", function() {
readURL(angular.element("#image_upload")[0]);
});
function readURL(input) {
if (input && input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function(e) {
angular.element("#preview_image").attr("src", e.target.result);
vm.base64File = e.target.result;
};
reader.readAsDataURL(input.files[0]);
}
}
For more info, read here and here
Update
var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope) {
$scope.file = '';
$scope.$watch("file", function() {
console.log($scope.file)
});
});
app.directive('fileModel', ['$parse', function($parse) {
return {
restrict: 'A',
link: function(scope, element, attrs) {
var model = $parse(attrs.fileModel);
var modelSetter = model.assign;
element.bind('change', function() {
scope.$apply(function() {
modelSetter(scope, element[0].files[0]);
});
});
}
};
}]);
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.js"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<label class="upload_image_label" for="image_upload">
choose file
<input id="image_upload" file-model="file" type="file" style="display:none" />
</label>
<hr> <br> File: {{file}}
</div>
</body>
</html>

As adardesign said
This is due to a security restriction.
I found out that the security restriction is only when the
<input type="file"/>
is set to display:none; or is visibility:hidden.
So i tried positioning it outside the viewport by setting
position:absolute and top:-100px; and voilĂ  it works.
You can find more in this post: Jquery trigger file input

Related

Image is not changing even i changed image

In angularjs if i change or remove image it does not make any changes. After refreshing the page it show the changed image.I am using following line to remove image
jQuery
$('#profile_image').val('')
This Sample is basic if you want to know more about AngularJs click on link
var app = angular.module("app", []);
app.controller("ctrl", [
"$scope",
function($scope) {
$scope.imgShow = true;
$scope.imgSrc = "https://www.gravatar.com/avatar/75025ad9a8cfdaa5772545e6e8f41133?s=32&d=identicon&r=PG&f=1";
$scope.display = function() {
$scope.imgShow = true;
$scope.imgSrc = "https://www.gravatar.com/avatar/75025ad9a8cfdaa5772545e6e8f41133?s=32&d=identicon&r=PG&f=1";
}
$scope.change = function() {
$scope.imgSrc = "https://www.gravatar.com/avatar/fccd71b79b3571b459cdfe40e7bf5dd8?s=32&d=identicon&r=PG&f=1";
}
$scope.remove = function() {
$scope.imgShow = false;
}
}
]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
<img ng-src="{{imgSrc}}" ng-show="imgShow">
<hr/>
<button ng-click="display()" ng-hide="imgShow">display image</button>
<button ng-click="change()">change image</button>
<button ng-click="remove()">remove image</button>
</div>
If you want to manipulate the DOM in AngularJS you should use directives for this purpose.
You should avoid using jquery inside of your controllers and simply work with your model. Below is fileUpload directive that could help you to work with <input type="file"> in a more angularjs-way:
angular.module('myApp', [])
.controller('TestController', ['$scope', function ($scope) {
var ctrl = this;
ctrl.imageFile = null;
ctrl.clearFile = clearFile;
function clearFile(){
ctrl.imageFile = null;
}
$scope.$ctrl = ctrl;
}])
.directive('fileUpload', [function () {
return {
require: "ngModel",
restrict: 'A',
link: function ($scope, el, attrs, ngModel) {
function onChange (event) {
//update bindings with $applyAsync
$scope.$applyAsync(function(){
ngModel.$setViewValue(event.target.files[0]);
});
}
//change event handler
el.on('change', onChange);
//set up a $watch for the ngModel.$viewValue
$scope.$watch(function () {
return ngModel.$viewValue;
}, function (value) {
//clear input value if model was cleared
if (!value) {
el.val("");
}
});
//remove change event handler on $destroy
$scope.$on('$destroy', function(){
el.off('change', onChange);
});
}
};
}]);
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="//code.angularjs.org/1.3.20/angular.js"></script>
<div ng-app="myApp">
<div ng-controller="TestController">
<input type="file" file-upload ng-model="$ctrl.imageFile" />
<input type="button" ng-click="$ctrl.clearFile()" value="Reset" />
<div ng-if="$ctrl.imageFile">
{{$ctrl.imageFile.name}}<br />
{{$ctrl.imageFile.size}} byte(s)<br/>
{{$ctrl.imageFile.type}}
</div>
</div>
</div>
UPDATE: Also take a look at this useful reading.

angularjs upload file using components

I am trying to upload file using angular component structure but i am not able to get the selected files.
Step 1:Template data.
<form name="form">
Hello {{vm.name}} <br />
Upload: <input my-directive type="file" name="file" ng-model="files" /> <br />
<input type="button" ng-click='vm.uploadFile()' value="Upload File." />
</form>
Step 2: Js file combined looks like
'use strict';
angular.module('app', ['ngFileUpload']);
class TestController {
constructor(){
this.name = 'user';
}
getFiles(selectedFiles){
console.log('Selected files are : ' + JSON.stringify(selectedFiles));
this.files = selectedFiles; // results empty data.
}
uploadFile (){
console.log('Model data i.e. files consists of : ' + JSON.stringify(this.files));
// Upload code will do later.
}
}
angular.module('app').directive('myDirective', function () {
return {
restrict: 'A',
scope: true,
link: function (scope, element, attr) {
element.bind('change', function () {
console.log('Value of element is :' + JSON.stringify(element[0].files[0]));
});
}
};
});
//Created a test controller here.
angular.module('app').controller('TestController', TestController);
// Created a component here.
angular.module('app').component('test', {
templateUrl: 'test.html',
controller: TestController,
controllerAs : 'vm',
});
Thanks in Advance, well i am new to angular :)
Sorry, I didn't notice that you were using typescript. I'm not really up to speed on ts at all yet. I answered a somewhat similar question that I can't find right now the other day with the code below. Note that there's an issue with ng-model and the file input type, so it uses document.getElementById to figure out the file. I suspect that this issue is what you're running into.
<html>
<body>
<form name="form" ng-app="app" ng-controller="Ctrl as ctrl">
Upload file:
<input type="file" id="file" ng-model="ctrl.file" />
<br/>
<br/> Enter text:
<textarea id="textarea" ng-model="ctrl.text"></textarea>
<br/>
<br/>
<button class="btn btn-primary btn-large" ng-click="ctrl.submitForm()">Submit</button>
</form>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.9/angular.min.js">
</script>
<script>
angular.module('app', []).controller('Ctrl', function() {
var vm = this;
vm.file = ""
vm.text = ""
vm.submitForm = function() {
// angular doesn't update the model for input type="file"
vm.file = document.getElementById('file').value;
var retVal = false ;
alert(vm.file);
alert(vm.text);
if (vm.file && ! vm.text)
{retVal = true}
else if (vm.text && ! vm.file)
{retVal = true}
else if (!vm.text && !vm.file)
{retVal = false}
else if (vm.text && vm.file)
{retVal = false}
if (!retVal) {
alert("Please specify either a file or text, not both!")
} else
alert("ok")
}
});
</script>
</html>

AngularJS - upload and display image using FileReader API (multiple files) [duplicate]

This question already has answers here:
Directive to get files input with ng-model [duplicate]
(1 answer)
ng-model for `<input type="file"/>` (with directive DEMO)
(13 answers)
Closed 5 years ago.
I use the following example, it works perfectly , but I'd like to upload multiple images simultaneously.
http://jsfiddle.net/kkhxsgLu/2/
<div ng-controller="MyCtrl">
<div ng-repeat="step in stepsModel">
<img class="thumb" ng-src="{{step}}" />
</div>
<input type='file' ng-model-instant onchange="angular.element(this).scope().imageUpload(this)" />
$scope.stepsModel = [];
$scope.imageUpload = function(element){
var reader = new FileReader();
reader.onload = $scope.imageIsLoaded;
reader.readAsDataURL(element.files[0]);
}
$scope.imageIsLoaded = function(e){
$scope.$apply(function() {
$scope.stepsModel.push(e.target.result);
});
}
Thank you kindly help me, I started with angularjs
SOLUTION:
http://jsfiddle.net/orion514/kkhxsgLu/136/
:)
<div ng-controller="MyCtrl">
<div ng-repeat="step in stepsModel">
<img class="thumb" ng-src="{{step}}" />
</div>
<input type='file' ng-model-instant
onchange="angular.element(this).scope().imageUpload(event)"
multiple />
$scope.stepsModel = [];
$scope.imageUpload = function(event){
var files = event.target.files; //FileList object
for (var i = 0; i < files.length; i++) {
var file = files[i];
var reader = new FileReader();
reader.onload = $scope.imageIsLoaded;
reader.readAsDataURL(file);
}
}
$scope.imageIsLoaded = function(e){
$scope.$apply(function() {
$scope.stepsModel.push(e.target.result);
});
}
Directive to get files input with ng-model (multiple files)
The AngularJS built-in <input> directive does not handle <input type=file>. One needs a custom directive for that.
<input type="file" files-input ng-model="fileArray" multiple>
The files-input directive:
angular.module("app").directive("filesInput", function() {
return {
require: "ngModel",
link: function postLink(scope,elem,attrs,ngModel) {
elem.on("change", function(e) {
var files = elem[0].files;
ngModel.$setViewValue(files);
})
}
}
})
The above directive adds a change listener that updates the model with the files property of the input element.
This directive enables <input type=file> to automatically work with the ng-change and ng-form directives.
The DEMO on PLNKR
Inline Demo of files-input Directive
angular.module("app",[]);
angular.module("app").directive("filesInput", 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" files-input ng-model="fileArray" multiple>
<h2>Files</h2>
<div ng-repeat="file in fileArray">
{{file.name}}
</div>
</body>
Zypps987, try using var file = files[0], not inside a loop.

Angular highlight/select all content inside <div> element Angular

How do we highlight and select all content inside a element on click using Angular JS ?.
It is easy to do using inputbox. But how do we do for element.
Help would be appreciated.
Thank you
This is what I have used so far.
HTML
<div ng-controller="appController" ng-app="app">
<input type="text" ng-model="content" ng-click="onTextClick($event)" />
</div>
JS
var app = angular.module('app', []);
app.controller('appController',
function ($scope) {
$scope.content = 'test';
$scope.onTextClick = function ($event) {
$event.target.select();
};
});
http://jsfiddle.net/onury/R63u5/
jsfiddle: http://jsfiddle.net/n63LhtcL/3/
Here is an updated directive to achieve it:
.directive('selectOnClick', function ($window) {
return {
link: function (scope, element) {
element.on('click', function () {
var selection = $window.getSelection();
var range = document.createRange();
range.selectNodeContents(element[0]);
selection.removeAllRanges();
selection.addRange(range);
});
}
}
});
Your markup:
<div select-on-click>
Some text...
<input type="text" ng-model="content" />
</div>

Angularjs file upload

html
<form method='POST' enctype='multipart/form-data' name="formName">
<div class="row">
<div class="col-md-6">
<input type="file" style="text-align: left" ng-model="value" class="btn"/>
</div>
<div class="col-md-2">
<input type="submit" value="upload" class="btn btn-info" ng-click="submitFile()"/>
</div>
</div>
</form>
AngularJs
$scope.submitFile = function(){
document.formName.action = 'http://xxx.xxx.xxx.xxx:8000/ww/up?s=' + $rootScope.reply.Sid; //$rootScope.reply.Sid is secession id
document.formName.submit();
};
I am trying to do a fileupload with AngularJs. Will this logic work?. My selected path is also coming as given below.
C:\fakepath\license.txt
Is this an error?
Note:
Our UI team was able to the fileupload with the below code. I was trying to attain the same thing in AngularJs
<body>
<form method='POST' enctype='multipart/form-data' action="http://xxx.xxx.xx.xxx:xxxx/yyy/yyyyyyyyy?s=3e3646ea-48cc-4342-a388-e0c0d7bbf4e4"/'>
File to upload: <input type=file id='up_file' name=upfile><br>
</body>
You did it right .. you only have to change few things to make it work
Change
<form method='POST' enctype='multipart/form-data' name="formName">
To
<form action="{{action}}" method='POST' enctype='multipart/form-data' name="formName">
In controller inject $timeout along with $scope
app.controller('Test', function($scope, $rootScope, $timeout){
$scope.submitFile = function(){
$scope.action = 'http://xxx.xxx.xxx.xxx:8000/ww/up?s=' + $rootScope.reply.Sid;
$timeout(function(){
document.formName.submit();
}, 100);
}
});
Action assigning $scope.action with new data .. angularjs needs to update the dom .. that is the reason we are using $timeout and submitting the form
I am providing an example of Upload File. To develop this app, we have used HTML, CSS and AngularJS. Following example shows about how to upload the file using AngularJS.
<html>
<head>
<script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
</head>
<body ng-app = "myApp">
<div ng-controller = "myCtrl">
<input type = "file" file-model = "myFile"/>
<button ng-click = "uploadFile()">upload me</button>
</div>
<script>
var myApp = angular.module('myApp', []);
myApp.directive('fileModel', ['$parse', function ($parse) {
return {
restrict: 'A',
link: function(scope, element, attrs) {
var model = $parse(attrs.fileModel);
var modelSetter = model.assign;
element.bind('change', function(){
scope.$apply(function(){
modelSetter(scope, element[0].files[0]);
});
});
}
};
}]);
myApp.service('fileUpload', ['$http', function ($http) {
this.uploadFileToUrl = function(file, uploadUrl){
var fd = new FormData();
fd.append('file', file);
$http.post(uploadUrl, fd, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
})
.success(function(){
})
.error(function(){
});
}
}]);
myApp.controller('myCtrl', ['$scope', 'fileUpload', function($scope, fileUpload){
$scope.uploadFile = function(){
var file = $scope.myFile;
console.log('file is ' );
console.dir(file);
var uploadUrl = "/fileUpload";
fileUpload.uploadFileToUrl(file, uploadUrl);
};
}]);
</script>
</body>
</html>
This is a working example with no other dependencies than AngularJS

Resources