Oron Bendavid
Oron Bendavid

Reputation: 1533

AngularJS - upload and display image using ng-repeat and jQuery

I'm trying to upload and display image inside ng-repeat.

I've succeeded to upload and display image without ng-repeat using jquery function:

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

if i change the code to be inside ng-repeat, the jQuery function dosent work:

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

2 questions:

  1. how can i change the jquery function to angular function?
  2. how can i make the ng-reapeat deal with the jquery function?

Many thanks

Upvotes: 0

Views: 9197

Answers (2)

Gal Weissman
Gal Weissman

Reputation: 208

Your code is "slightly" problematic in many aspects. It seems like you're new to AngularJS - so, welcome.

While referring to your code, it looks like stepsModel is a variable that is relative to your current $scope. When $scope.sepsModel is updated, Angular's data binding will take charge and keep your HTML updated with your new data: https://docs.angularjs.org/tutorial/step_04

As for your question, your goal should be to add an image into $scope.stepsModel upon upload. $scope.stepsModel will be auto overviewed in the HTML with all the uploaded images.

It is somehow unnecessary to use jQuery for the purpose you intended. Just so you could learn better and for the good spirit I've made a suggestion on how it should be done, using your own state of mind:

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);
    });
}

Good luck.

Upvotes: 6

Omar Enrico Polo
Omar Enrico Polo

Reputation: 331

I think you need to create a service (see this ) and put your jQuery code into that service. For the second question I ask you tu show us the code.

Upvotes: 0

Related Questions