angular file upload in ng-repeat with preview input bind - angularjs

I'm working on an angular 1.6 based image upload with ng-repeat, note the input is not multi, but there are multiple ng-repeated inputs, I have the image preview working as well as adding lines / removing lines, the only thing that seems to not be working is if I remove an item the file inputs do not update (I have code that does properly update the previews). Here is what I am working with:
<div ng-repeat="item in data.items track by $index">
<input ng-model="item.fileinput" type="file" name="image_{{$index}}" id="image_{{$index}}" onchange="angular.element(this).scope().imageChoose(this)"/><i ng-click="removeEvent($index)" class="fa fa-trash fa-lg"></i>
<img ng-if="!item.thumb" class="preview-image-small" ng-src="/images/general/placeholder.jpg"</img>
<img ng-if="item.thumb" class="preview-image-small" ng-src="{{item.thumb}}"</img>
</div>
Then in my controller I handle the imageChoose as follows:
$scope.imageChoose = function (data) {
var id = data.id.split("_");
id = id[id.length-1];
var elem = document.getElementById(data.id);
if (typeof (FileReader) != "undefined") {
var reader = new FileReader();
reader.onload = function (e) {
$scope.$apply(function() {
$scope.data.data.items[id].thumb = e.target.result;
});
};
reader.readAsDataURL(elem.files[0]);
} else {
alert("This browser does not support FileReader.");
}
};
This properly sets the image previews and when I run a remove on a line they re-order correctly due to the ng-src of event.thumb. The problem is the actual file input does not bind or update, here is the code for removing a line:
$scope.removeEvent = function (index) {
$scope.data.items.splice(index, 1);
};
I'm hoping there is a relatively simple way to bind the input or handle the remove so that the inputs stay correct. Thanks in advance for any ideas.

Your removeEvent method is not working because of using track by $index together with ng-repeat. This is a known side effect. Try removing it/using different track by expressions.

Related

AngularJs Component doesn't update view after img loading

i'm using angularJs 1.7 components.
This is my component who uploads a picture then converts it to base 64, then it is supposed to display it, but the displaying doesnt work .
myApp.component('club', {
templateUrl: 'vues/club.html',
controller: function($log,$scope) {
// HTML form data, 2 way binding ..
this.club = {};
// Bse 64 encoder
encodeImageFileAsURL = function() {
var filesSelected = document.getElementById("inputFileToLoad").files;
if (filesSelected.length > 0) {
var fileToLoad = filesSelected[0];
var fileReader = new FileReader();
fileReader.onload = function(fileLoadedEvent) {
var srcData = fileLoadedEvent.target.result; // <--- data: convert base64 : OK
this.club.img = srcData ; // Displaying in view doesnt work
}
fileReader.readAsDataURL(fileToLoad);
}
}
// Jquery watcher when we upload a picture
$(document).on('change', 'input[type="file"]' , function(){
encodeImageFileAsURL();
});
This is the html button inside the template :
<div id="upload_button">
<label>
<input name="inputFileToLoad" id="inputFileToLoad" ng-model="logo" type="file" onchange="" /> </input>
<span class="btn btn-primary">Upload picture</span>
</label>
</div>
This is the error :
TypeError: this.club is undefined
srcData is ok, and holds a base 64 image, the function works well.
I've tried the solution provided (.bind(this)) there with no luck , i dont know where to place it:
How to access the correct `this` inside a callback?
When using the $scope syntax, it is working, adding $scope.$apply(), but now i'm using components based dev, and the .this syntax, it doesnt work any more .
EDIT 1 :
Ok, i've initialized club with
$scope.club = {} ;
then inside the function, i'm writing
$scope.club.img = srcData ;
Then, it is working ok. I dont understand why .this is not the same than $scope !
See following example for where this object has reference to
a={
firstname:"something",
lastname:"something2",
fullname:function(){
console.log(this.firstname+' '+this.lastname);
}
}
a.fullname();
In above example Object a is created and inside fullname() function this object pointing to 'a' Object.
So that in your case
templateUrl is only variable on this Object if you do not want to use $scope. You can declare it by using var club = {}

AngularJs Auto Complete Search

So this works with static data, but when I push data with a $http this autocomplete does not work. The data pushes to the empty array of airport_list but something is happening when I try to use airport_list in for the autocomplete. Not sure what is is. I can only find answers which pertain to static data.
This is updated per everyones help.
Here is the controller
app.controller('selectCtrl', function($scope, $http) {
$scope.airport_list = null;
$http({
url: 'someUrl.com',
method: 'GET'
})
.then((response) => {
angular.forEach(response.data.airports, function(value, key) {
$scope.airport_list = response.data.airports;
})
$scope.airports = $scope.airport_list;
});
$scope.selectAirport = function(string) {
$scope.airport = string;
$scope.hidelist = true;
};
})
Here is the template
<div class="control">
<div>
<input
type="text"
name="airport"
id="airport"
ng-model="airport"
ng-change="searchFor(airport)"
placeholder="From..."
/>
<div class="airport-container-dropdown" ng-hide="hidelist">
<div
class="airport-list"
ng-repeat="airport in airports"
ng-click="selectAirport(airport)"
>
{{ airport.name }}
</div>
</div>
</div>
</div>
I really would like to do this without using bootstrap typeahead.
Thank you for looking at this.
I have made changes as recommended by below answers and the $http request is feeding into the autocomplete as a whole list but searching by name does not work and clicking on name sets [object, object]
this would be the code which is specific to that functionality.
$scope.searchFor = function(string) {
$scope.hidelist = false;
const output = [];
angular.forEach($scope.airport_list, function(airport) {
if (airport[0].toLowerCase().indexOf(string.toLowerCase(airport)) >=
0) {
output.push(airport);
}
});
$scope.airports = output;
};
$scope.selectAirport = function(string) {
$scope.airport = string;
$scope.hidelist = true;
};
Try this:
$scope.airport_list = response.data.airports;
What I am seeing is that you have an array: $scope.airport_list = [];
When you make your http request, you push what I would understand to be an array of airports into that array. So you end up with your airport array from the backend at the first position of $scope.airport_list, vs. $scope.airport_list being the actual list.
For your search method, you should change the following:
In your HTML:
ng-change="searchFor(airport.name)"
In your JS:
I've renamed your function and changed the input variable to be more clear. You were passing in a full airport, but treating it as a string. You need to compare your provided airport name to that of the airports in the array. So you iterate over the array, and compare each element's name property to what you pass in.
$scope.searchFor = function(airportName) {
$scope.hidelist = false;
const output = [];
angular.forEach($scope.airport_list, function(airport) {
if (airport.name.toLowerCase() === airportName) {
output.push(airport);
}
});
$scope.airports = output;
console.log($scope.airports);
};
I have provided minimal changes to your code to implement this, however I suggest you look at this SO post to filter drop down data more appropriately.
Angularjs Filter data with dropdown
If you want to simply filter out what is displayed in the UI, you can try this in your HTML template. It will provide a text field where you supply a partial of the airport name. If at least one character is entered in that box, the list will display on the page, with the appropriate filtering applied. This will avoid having to call functions on change, having a separate array, etc.
<input type="text" name="airport" id="airport" ng-model="airportSearch.name" placeholder="From..." />
<div class="airport-container-dropdown" ng-hide="!airportSearch.name">
<div class="airport-list"
ng-repeat="airport in airport_list | filter:airportSearch"
ng-click="selectAirport(airport)">
{{ airport.name }}
</div>
</div>

how to hide dropdown md-autocomplete

How to Hide AutoComplete Dropdown after selected item i try many types but not success , anyone help me this , highly appreciated
<md-autocomplete id="autocomplete" st-search="campaign_name"
ng-disabled="Ctrlmain.isDisabled"
md-no-cache="true"
md-selected-item="Ctrlmain.selectedItem"
md-search-text="Ctrlmain.campaignname"
md-selected-item-change="Ctrlmain.filltextbox(item)"
md-items="item in Ctrlmain.getMatches(Ctrlmain.campaignname) | unique:'campaign_name'"
md-item-text="item.campaign_name"
md-min-length="0"
placeholder="Search Campaign"
md-menu-class="autocomplete-custom-template">
<md-item-template>
<span class="item-title">
<span> {{item.campaign_name}} </span>
</span>
</md-item-template>
</md-autocomplete>
Angularjs Code
filltextbox(st){
var autoChild = document.getElementById('autocomplete').firstElementChild;
console.log(autoChild)
var el = angular.element(autoChild);
console.log(el)
el.scope().$mdAutocompleteCtrl.hidden = true;
// return st;
}
I find in these scenarios it is often another $digest or DOM affecting async function that gets in the way of the standard close logic working. The quick hack is to try to close the dialog after a $timeout.
If you have other async processes running on the page, perhaps like executing a search query, and while the search is running a full screen loader is written into the DOM then it might be necessary to set the $timeout delay to a larger value than usual.
The following snippet tries to force the close immediately, and after a timeout to cover all bases, I use this for my md-autocompletes that are serving as a search input with best bet suggestions as well as search results.
filltextbox(st){
closeAutocomplete();
$timeout(closeAutocomplete, 100);
// return st;
}
closeAutocomplete () {
var autoChild = document.getElementById('autocomplete').firstElementChild;
var el = angular.element(autoChild);
el.scope().$mdAutocompleteCtrl.hidden = true;
}
For good measure, I make sure the other async functions that operate on the page also call closeAutocomplete. You could wrap the immediate and $timeout logic into a single call like this that allows you to pass in a variable delay
closeAutocomplete (delay) {
// declare function once, only one point to maintain
var fn = function() {
var autoChild = document.getElementById('autocomplete').firstElementChild;
var el = angular.element(autoChild);
el.scope().$mdAutocompleteCtrl.hidden = true;
};
fn(); // immediate
if(!delay) delay = 100;
$timeout(fn, delay);
}

cannot get input value of Struts 2 file selector with Angular

I am using Angular and I want to get access to the file input field's file name attributes and display it in another input box.
This is the file upload field:
<div class="btn btn-orange btn-file col-sm-3" >
<s:text name="expedientes.btn.seleccionar.fichero" />
<s:file name="form.filesUpload" multiple="multiple" ng-model="filesUploadModel" id="filesUploadId"/>
</div>
And the input box to show file name:
<input type="text" class="form-control"
id="fileNameId" name="fileName"
ng-model="fileNameModel" ng-disabled="true"
ng-init="" ng-bind="fileNameModel = filesUploadModel">
But the ng-bind is not working.
I also tried to define $watch for the file input field like this:
$scope.$watch(function() {
$scope.files = angular.element(document.querySelector('#filesUploadId'));
return files;
},
function(newValue, oldValue) {
$("#fileNameId").val(files.files[0].name);
});
to watch if the <input type="file" id="filesUploadId"> has changed, select this element and return it as files, and let the element with id fileNameId's value equals to files.files[0].name, because the file upload input has an attribute named files with all the files I upload, and their file names files[i].name.
But FF tells me files is undefined and no avail. It's not working.
Am I doing something wrong here? Please help and thanks!!
Edit: I am using this and no error, but no result either:
if (!angular.equals(document.getElementById("filesUploadId"), null)) {
$scope.$watch(function() {
var myFiles = document.getElementById("filesUploadId");
return myFiles;
},
function(newValue, oldValue) {
$( "#fileNameId" ).val(function(){
var result = null;
$(myFiles).each(function(){
result = name + this.attr(files).attr(name);
});
return result;
});
});
}
I solved it with pure JavaScript, enlighted by another question here:
AngularJs: How to check for changes in file input fields?
Actually, I find it impossible to use onchange() when the function I want to call is wrapped in angular module, except in the way in above answer:
onchange="angular.element(this).scope().setFileName()"
And in my script I only use pure JavaScript, except for the definition of the function:
angular.module('es.redfinanciera.app').controller('PanelMandarCorreoCtrl', function ($scope, $modalInstance) {
....(other functions)
$scope.setFileName = function() {
var result = "";
var adjuntos = document.getElementById("filesUploadId").files;
for (i = 0; i < adjuntos.length; i++){
result = result + adjuntos[i].name + "\r\n";
};
document.getElementById("fileNameId").value = result;
}
}
$scope.btnClean = function() {
document.getElementById("filesUploadId").value = "";
document.getElementById("fileNameId").value = "";
};
And in my jsp page, finally I have my file upload button and a clean button like this:
<div class="btn btn-orange btn-file col-sm-3" >
<s:text name="expedientes.btn.seleccionar.fichero" />
<s:file name="correoForm.filesUpload" id="filesUploadId" multiple="multiple" ng-model="filesUploadModel"
onchange="angular.element(this).scope().setFileName()"/>
</div>
<div class="col-sm-2">
<button class="btn btn-default btn-normal" type="button" ng-click="btnClean()">
<s:text name="expedientes.btn.quitar.fichero" />
</button>
</div>
I have a <textarea> to display all the file names:
<textarea class="form-control" ng-model="fileNameModel"
name="fileName" id="fileNameId"
ng-disabled="true"></textarea>
EDIT:
Clear button is not working in IE8 because it is not permitted in IE8 to set "" value to a file input field. My guess is, I can remove this file input field and copy a new one, with same style but no file is selected. But I have found a good question who has amounts of answers here:
clearing-input-type-file-using-jquery
Also, I heard that in IE8 onchange() event will not be triggered if you only select a file, you must add this.blur() after selecting a file. Regarding this issue, IE is following strictly the spec, but FF is not. But in my case, the event is actually triggered. Maybe because I am testing under IE 11 using Developing Tools' emulator for IE8.

How do I change AngularJS ng-src when API returns null value?

In working with the API from themoviedb.com, I'm having the user type into an input field, sending the API request on every keyup. In testing this, sometimes the movie poster would be "null" instead of the intended poster_path. I prefer to default to a placeholder image to indicate that a poster was not found with the API request.
So because the entire poster_path url is not offered by the API, and since I'm using an AngularJS ng-repeat, I have to structure the image tag like so (using dummy data to save on space):
<img ng-src="{{'http://example.com/'+movie.poster_path}}" alt="">
But then the console gives me an error due to a bad request since a full image path is not returned. I tried using the OR prompt:
{{'http://example.com/'+movie.poster_path || 'http://example.com/missing.jpg'}}
But that doesn't work in this case. So now with the javascript. I can't seem to get the image source by using getElementsByTagName or getElementByClass, and using getElementById seems to only grab the first repeat and nothing else, which I figured would be the case. But even then I can't seem to replace the image source. Here is the code structure I attempted:
<input type="text" id="search">
<section ng-controller="movieSearch">
<article ng-repeat="movie in movies">
<img id="myImage" src="{{'http://example.com/'+movie.poster_path}}" alt="">
</article>
</section>
<script>
function movieSearch($scope, $http){
var string,
replaced,
imgSrc,
ext,
missing;
$(document).on('keyup', function(){
string = document.getElementById('search').value.toLowerCase();
replaced = string.replace(/\s+/g, '+');
$http.jsonp('http://example.com/query='+replaced+'&callback=JSON_CALLBACK').success(function(data) {
console.dir(data.results);
$scope.movies = data.results;
});
imgSrc = document.getElementById('myImage').src;
ext = imgSrc.split('.').pop();
missing='http://example.com/missing.jpg';
if(ext !== 'jpg'){
imgSrc = missing;
}
});
}
</script>
Any ideas with what I'm doing wrong, or if what I'm attempting can even be done at all?
The first problem I can see is that while you are setting the movies in a async callback, you are looking for the image source synchronously here:
$http.jsonp('http://domain.com/query='+replaced+'&callback=JSON_CALLBACK').success(function(data) {
console.dir(data.results);
$scope.movies = data.results;
});
// This code will be executed before `movies` is populated
imgSrc = document.getElementById('myImage').src;
ext = img.split('.').pop();
However, moving the code merely into the callback will not solve the issue:
// THIS WILL NOT FIX THE PROBLEM
$http.jsonp('http://domain.com/query='+replaced+'&callback=JSON_CALLBACK').success(function(data) {
console.dir(data.results);
$scope.movies = data.results;
// This will not solve the issue
imgSrc = document.getElementById('myImage').src;
ext = img.split('.').pop();
// ...
});
This is because the src fields will only be populated in the next digest loop.
In your case, you should prune the results as soon as you receive them from the JSONP callback:
function movieSearch($scope, $http, $timeout){
var string,
replaced,
imgSrc,
ext,
missing;
$(document).on('keyup', function(){
string = document.getElementById('search').value.toLowerCase();
replaced = string.replace(/\s+/g, '+');
$http.jsonp('http://domain.com/query='+replaced+'&callback=JSON_CALLBACK').success(function(data) {
console.dir(data.results);
$scope.movies = data.results;
$scope.movies.forEach(function (movie) {
var ext = movie.poster_path && movie.poster_path.split('.').pop();
// Assuming that the extension cannot be
// anything other than a jpg
if (ext !== 'jpg') {
movie.poster_path = 'missing.jpg';
}
});
});
});
}
Here, you modify only the model behind you view and do not do any post-hoc DOM analysis to figure out failures.
Sidenote: You could have used the ternary operator to solve the problem in the view, but this is not recommended:
<!-- NOT RECOMMENDED -->
{{movie.poster_path && ('http://domain.com/'+movie.poster_path) || 'http://domain.com/missing.jpg'}}
First, I defined a filter like this:
In CoffeeScript:
app.filter 'cond', () ->
(default_value, condition, value) ->
if condition then value else default_value
Or in JavaScript:
app.filter('cond', function() {
return function(default_value, condition, value) {
if (condition) {
return value;
} else {
return default_value;
}
};
});
Then, you can use it like this:
{{'http://domain.com/missing.jpg' |cond:movie.poster_path:('http://domain.com/'+movie.poster_path)}}

Resources