Jorge
Jorge

Reputation: 18237

Cannot update model of directive

I can't understand why if I add more elements to my array inside of a controller of one directive, are not showed in the view and worst is that if I print my model it doesn't show the newest elements added

Here's how I defined my directives

angular.module('example',[]);

angular.module('example').directive('documentUpload', function() {

function link($scope, $element, attrs, ngModelCtrl) {
    $element.find('input[type="file"]').on('change', function (){
        $scope.submitFile(this);    
    });
}

return {
    restrict: 'E',
    templateUrl: 'document-upload.html',
    controller: function($scope,$element) {
        $scope.files = [{ name : "blah", src: "blah" }];
        $scope.submitFile = function(file,container) {
            var currentFile = file.files[0];
            var reader  = new FileReader();
            reader.onloadend = function(){
                $scope.files.push({
                    name: currentFile.name,
                    src : reader.result
                });
                console.log($scope.files);
                console.log($scope.example);
            }

            reader.readAsDataURL(currentFile);
        };
    },
    alias: 'document',
    link: link
}

}).directive('imageFiles', function($compile) {
    return {
        scope: {
            file: "="
        },
        template: '<img ng-model="file" ng-src="file.src" alt="file.name" class="img-responsive"/>'
    }
});

And if I tried to see the model in the view is not showing the newest element added,

<div class="row">
<pre>{{ files }}</pre>
<div class="col-lg-12">
    <form method="POST" enctype="multipart/form-data" ng-submit="submit(document)">
      <input type="file" name="file" ng-model="document.file"/>           
    </form>
</div>
<div class="row" ng-repeat="file in files" image-files>

Here's a live Example

Upvotes: 0

Views: 28

Answers (1)

ribsies
ribsies

Reputation: 1218

Ok so here is what is happening. Since you are using reader.onloadend which is an external function or plugin, whatever it is. It is missing the internal angular digest process.

This is a case where you need to add $scope.$apply() after you push to the array.

$scope.files.push({
   name: currentFile.name,
   src : reader.result
});
$scope.$apply();

This forces angular to refresh itself.

Here is a working plunker just to be safe.

http://plnkr.co/edit/w3u3VWMC9e8h1L0Bhkuh?p=preview

Upvotes: 1

Related Questions