2014-10-08 61 views
0

我試圖在ng-repeat內部上傳和顯示圖像。AngularJS - 使用ng-repeat和jQuery上傳和顯示圖像

我已經成功使用jQuery功能上傳和顯示圖像不NG-重複:

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

如果我改變的代碼在裏面NG-重複,jQuery函數dosent工作:

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

2個問題:

  1. 如何更改jQuery的功能角度的功能?
  2. 我如何使ng-reapeat處理jquery函數?

非常感謝

+0

您必須提供一些代碼和html ... – 2014-10-08 10:51:11

+0

嗨,感謝您的更新,代碼提供:) – 2014-10-08 11:13:11

回答

6

您的代碼在許多方面「略有」問題。 看起來你是AngularJS的新手 - 所以,歡迎。

引用您的代碼時,它看起來像stepsModel是一個相對於您當前的$ scope的變量。 當$ scope.sepsModel更新,角的數據綁定會負責,並保持你的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); 
    }); 
} 

好運。

+0

嗨加侖,謝謝!很棒的解決:) – 2014-10-09 07:32:25

0

我想你需要創建一個服務(見this),把你的jQuery代碼到該服務。 對於第二個問題,我問你,讓我們看看代碼。

+0

嗨,感謝您的更新,仍然在尋找解決方案。 – 2014-10-08 15:04:35