AngularJS - 使用ng-repeat和jQuery上传和显示图像

Oro*_*vid 0 html jquery image-uploading angularjs angularjs-ng-repeat

我正在尝试上传并在ng-repeat中显示图像.

我已成功使用jquery函数上传和显示没有ng-repeat的图像:

<html>
<head>
        <script src="jquery.js" type="text/javascript"></script>
</head>
<body>
<input type='file' />
<img id="myImg" ng-src="#" alt="your image" style="width:50px;height:50px"/>
</body>
</html>
...
<script>
$(function () {
    $(":file").change(function () {
        if (this.files && this.files[0]) {
            var reader = new FileReader();
            reader.onload = imageIsLoaded;
            reader.readAsDataURL(this.files[0]);
        }
    });
});

function imageIsLoaded(e) {
    $('#myImg').attr('src', e.target.result);
};
</script>
Run Code Online (Sandbox Code Playgroud)

如果我将代码更改为ng-repeat内部,则jQuery函数可以正常工作:

<div ng-repeat="step in stepsModel">
 <input type='file' />
 <img id="myImg" ng-src="#" alt="your image" style="width:50px;height:50px"/>
/div>
Run Code Online (Sandbox Code Playgroud)

2个问题:

  1. 如何将jquery函数更改为角度函数?
  2. 如何使用ng-reapeat处理jquery函数?

非常感谢

小智 6

您的代码在许多方面都存在"轻微"问题.看起来你是AngularJS的新手 - 所以,欢迎.

在引用代码时,看起来stepModel是一个相对于当前$ scope的变量.当$ scope.sepsModel更新时,Angular的数据绑定将负责并使用您的新数据更新HTML:https: //docs.angularjs.org/tutorial/step_04

至于你的问题,你的目标应该是在上传时将图像添加到$ scope.stepsModel中.$ scope.stepsModel将在HTML中自动概述所有上传的图像.

在某种程度上,不必将jQuery用于您的预期目的.只是这样你可以更好地学习,并且为了良好的精神,我已经根据自己的心态提出了应该如何做的建议:

http://jsfiddle.net/kkhxsgLu/2/

    $scope.imageUpload = function(element){
    var reader = new FileReader();
    reader.onload = $scope.imageIsLoaded;
    reader.readAsDataURL(element.files[0]);
}

$scope.imageIsLoaded = function(e){
    $scope.$apply(function() {
        $scope.stepsModel.push(e.target.result);
    });
}
Run Code Online (Sandbox Code Playgroud)

祝好运.