无法更新指令的模型

时间:2015-03-02 22:52:54

标签: javascript angularjs

我无法理解为什么如果我在一个指令的控制器中向我的数组中添加更多元素,在视图中没有显示,最糟糕的是如果我打印我的模型它没有显示添加了最新元素

这是我如何定义指令

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"/>'
    }
});

如果我试图看到视图中的模型没有显示添加的最新元素,

<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>

这是一个实时的Example

1 个答案:

答案 0 :(得分:1)

好的,这就是正在发生的事情。因为您使用的是reader.onloadend,它是一个外部函数或插件,无论它是什么。它缺少内部角度消化过程。

这是你需要在推送到数组后添加$ scope。$ apply()的情况。

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

这会迫使角度自我刷新。

这是一个安全的工作人员。

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