ng-repeat未在FileReader上处理

新奇的

所以这就是我的看法:

<body ng-controller="AdminCtrl">
<img ng-repeat="pic in pics" ng-src="{{pic}}" />
<form ng-submit="postPic()">
    <input id="photos" type="file" accept="image/*" multiple/>
    <button>Add Pics</button>
</form>

这是控制器:

app.controller('AdminCtrl',['$scope', function($scope){
    $scope.pics =[];

    $scope.postPic = function() {
        var files = $('#photos').get(0).files;

        for (var i = 0, numFiles = files.length; i < numFiles; i++) {
            var photoFile = files[i];
            var reader = new FileReader();
            reader.onloadend = function(e){
                $scope.pics.push(e.target.result);
                console.log($scope.pics);
            };
            reader.readAsDataURL(photoFile);
        }
    };

尽管我选择了许多文件,它们也同时显示在控制台中(尽管是异步的),但我似乎无法根据的更新来更新视图$scope.pics$scope.pics被监视吗?为什么会这样呢?

香蕉

问题是您正在异步更改$ scope对象,因此angular无法意识到它需要处理的更改。Angular不会不断“监视”您的$ scope对象。通常不需要显式使用$scope.$apply()的原因是,如果您位于角度生态系统内(例如:控制器构造函数,$ scope函数等),那么angular大部分时间会自动为您执行此操作。

app.controller('AdminCtrl',['$scope', function($scope){
    $scope.pics =[];

    $scope.postPic = function() {
        var files = $('#photos').get(0).files;

    for (var i = 0, numFiles = files.length; i < numFiles; i++) {
        var photoFile = files[i];
        var reader = new FileReader();
        reader.onloadend = function(e){
            $scope.pics.push(e.target.result);
            console.log($scope.pics);
            $scope.$apply(); // force digest cycle
         };
         reader.readAsDataURL(photoFile);
    }
};

这与angular提供$timeout服务的原因相同,后者只是包装器,setTimeout但会自动为您触发摘要周期:https : //stackoverflow.com/a/19609851/580487

TLDR;异步功能(除了内置的角度对象外)在角度生态系统之外,因此您必须通过以下方式告知角度有关$ scope变化的信息$scope.$apply()

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章