【问题标题】:ng-repeat not processing upon FileReaderng-repeat 不在 FileReader 上处理
【发布时间】:2015-05-09 17:37:52
【问题描述】:

这就是我的观点:

<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不是被监视了吗?为什么会这样?

【问题讨论】:

    标签: javascript angularjs filereader


    【解决方案1】:

    问题在于您正在异步更改 $scope 对象,因此 Angular 不知道它需要处理的更改。 Angular 不会一直“监视”你的 $scope 对象。您通常不必显式使用 $scope.$apply() 的原因是,如果您在 Angular 生态系统中(即:控制器构造函数、$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;异步功能 [除了内置的 Angular 东西] 不在 Angular 生态系统中,所以你必须通过 $scope.$apply() 让 Angular 知道 $scope 的变化。

    【讨论】:

    • 另一个问题,如果我在这个上面定义一个模型:&lt;input id="photos" ng-model="photos" type="file" accept="image/*" multiple/&gt; 为什么我不能在这里的控制器中设置类似var files = $scope.photos 的东西? $scope.photos 好像是undefined
    • 我不认为 Angular 内置了对此的支持。我会查看:stackoverflow.com/a/29018763/580487github.com/angular/angular.js/issues/1375
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-25
    • 2023-04-10
    • 2023-03-22
    • 2017-07-13
    • 2012-09-02
    • 2014-08-06
    相关资源
    最近更新 更多