I have a problem with the AngularJSng-repeat
directive , I am creating a banner component that works as follows: clicking on add image converts said image to and adds the new image to a and it is with this that the route is made of the . The code I have is the following:base64
array
array
ng-repeat
<div class="img" ng-repeat="imagen in imagenes track by $index">
<div class="cont_img">
<img src="{{ imagen.imagen }}" alt="" class="img-responsive imagen">
</div>
</div>
and in the Controller:
$scope.imagenes = [];
$scope.cambioUpload = function($file){
var reader = new FileReader();
reader.readAsDataURL($file.value[0]);
var dataURL = '';
reader.onload = function(){
dataURL = reader.result;
$scope.imagenes.push({
temporal : $scope.imagenes.length + 1,
imagen: dataURL,
tiempo: 0
});
}
}
The problem is that the new image that was added is not updated in real time, it only appears when clicking anywhere on the page, I don't know why this is happening.
It's because adding the element outside the loop
$digest
of angular.When the function is executed
$scope.cambioUpload
, any model that is updated between the start and end of the function will be updated in the view. Now, the eventFileReader#onload
breaks that rule and its execution starts when the image loads, which means that the execution of the method$scope.cambioUpload
has finished. In other words: its execution is asynchronous. And since the $digest has already finished, the changes in the view will not be updated until another$digest
.This is what happens in your case:
Note that in the case of onload, $digest is not called to update the view. so you have to force the
$digest
con$apply()
to update the view once the method is executedonload
: