文件上传:视图未在非角度事件上更新

时间:2012-10-10 16:09:23

标签: javascript angularjs

我正在尝试创建一个上传组件,但是当onchange事件触发时我的视图没有更新。我看到file.names被记录但没有发生任何事情。

我正在使用指令,因为我希望能够将我的包放入项目中,然后使用<upload url='/fileserver'></upload>启用文件上传器。

控制器:

var controllers = {

  UploadCtrl: function ($scope) {

    $scope.images = [];
    $scope.files = [];

    $scope.upload = function (element) {
      $scope.$apply(function ($scope) {
        $scope.files = element.files;
      });
    };

    $scope.$watch('files', function () {

      for (var i = 0; i < $scope.files.length; i += 1) {

        var current = $scope.files[i];
        var reader = new FileReader();

        reader.onload = (function (file) {
          return function (env) {
            console.log(file.name);
            $scope.images.push({ name: file.name, src: env.target.result });
          }
        }(current));

        reader.readAsDataURL(current);
      }

    }, true);

  }

};

指令:

var directives = {

  upload: function ($compile) {

    return {
      restrict: 'E',
      link: function (scope, element, attr) {
        scope.url = element.attr('url');
        element.html($compile(template)(scope));
      }
    };

  }

};

模板var(它是多行字符串的cs文件原因)

template = """
<div ng-controller='UploadCtrl'>
  <input type='file' multiple onchange='angular.element(this).scope().upload(this)' />

  <div ng-repeat='image in images'>
    {{image.name}}: <img ng-src='{{image.src}}' width='80' height='80' />
  </div>
</div>
"""

1 个答案:

答案 0 :(得分:5)

您可能需要使用$ apply来更新图片:

$scope.$apply(function () {
    $scope.images.push({ name: file.name, src: env.target.result });
}