0

I have an interesting question concerning AngularJs. I am attempting to create a dynamic list of image files which the user can add to an array before he/she submits them. I would like the added files name to be displayed in the list using ng-repeat.

<h5>Images</h5>                                        
<ul>
    <li data-ng-repeat="image in images">
        {{image.name}}
    </li>
</ul>
<button type="button" data-ng-click="addImage()">ADD IMAGE</button>

Basically, the user clicks on the "add image" button above and the file selector dialog will appear. Once the user has selected a file, the details are added to the array. This all works fine... however, the ng-repeat directive is not updated. Why would this be?

app.controller('ImagesController', ['$scope', function($scope) {
    $scope.init = function() {
        $scope.images = [];
    };
    $scope.init();

    $scope.addImage = function() {
        input = document.createElement('input');
        input.type = "file";
        input.onchange = function() {
            $scope.images.push({
                name: input.value.split(/(\\|\/)/g).pop(),
                file: input.files[0]
            });
        };
        setTimeout(function(){
            $(input).click();
        }, 200);        
    };
}]);

1 Answer 1

3

This callback is happening outside of the scope of the Angular app.

Try adding $scope.$apply(); after you push the new value in to manually fire the digest. There are sometimes better ways to do this, but this will at least confirm that it's the issue.

input.onchange = function() {
  $scope.images.push({
    name: input.value.split(/(\\|\/)/g).pop(),
    file: input.files[0]
   });
  $scope.$apply()
};
1
  • Right you are. I knew it had something to do with scope. Commented Sep 3, 2014 at 18:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.