[英]angularjs image src change when model changes
我正在服務器上旋轉圖像,我想知道如何在我的頁面上顯示圖像更改?
我想我必須使用$ scope。$ apply()但每次我使用它時都會收到錯誤消息“正在進行摘要循環”
template.html
< img src='{{tempimagefilepath}}/> <!--image-->
controller.js
photoalbumServ.rotate_photo(post).then(function(data) {
//after server modifies photo
$scope.tempimagefilepath = $scope.baseurl + "user_images/user_43/temp/123-temp.jpg";
$scope.$apply();
});
謝謝
解:
我的解決方案是更改范圍值{{tempimagefilepath}},以便圖像更改。 這要求我在旋轉圖像時不斷重命名服務器上的文件。
兩件事情。 首先,您應該使用ng-src
而不是src
來防止客戶端在angular評估表達式之前嘗試加載圖像。
其次,傳遞$apply()
函數回調,以進行必要的范圍更改:
photoalbumServ.rotate_photo(post).then(function(data) {
//after server modifies photo
$scope.$apply(function() {
$scope.tempimagefilepath = $scope.baseurl + "user_images/user_43/temp/123-temp.jpg";
});
});
我認為這是因為您的瀏覽器緩存。 不需要$ apply()
嘗試這個
var random = (new Date()).toString();
$scope.tempimagefilepath = newUrl + "?cb=" + random;
您可以嘗試使用ng-src
而不是src
<img ng-src="{{tempimagefilepath}}" />
我認為你不需要做范圍。$ apply(); 然后
我有同樣的問題,我有一個<user-picture>
指令,在用戶設置頁面上,用戶可以更改他的圖片。 圖片來自api like url + token
。 當我從數據庫中更改圖片時,我獲得了成功,然后我需要在指令的每個實例上更新ng-src="{{mainCtrl.picture.src}}"
文件。
這是指令:
angular.module('appApp') .directive('userPicture', function() { return { restrict: 'E', template: '<img class="img-responsive" ng-src="{{mainCtrl.picture.src}}" />', controller: 'UserPictureCtrl', scope: true, replace: true } }) .controller('UserPictureCtrl',['$scope', '$resource', 'HelpersService', '$sessionStorage', function ($scope, $resource, HelpersService, $sessionStorage) { $scope.mainCtrl.picture = {}; $scope.mainCtrl.picture.src = HelpersService.domain + 'user/getPictureAsStream?token=' + $sessionStorage.token; }]);
ng-src="url file address string"
。
當我更改數據庫上的圖片時,我將$ scope.mainCtrl.picture.src的值重新分配給相同的url +標記,但是我都播種了一個額外的&rand
url參數播種網址如下所示: http://<domain>/<serverApi>/user/getPictureAsStream?token=65145d12-f033-41f1-b101-9ed846352284&rand=0.6513215699
,注意最后一個參數, &rand=0.6513215699
。
這告訴瀏覽器它是一個與不同url不同的文件並向服務器發出get請求,而在服務器上則忽略了額外的參數,即使它位於同一個地方。
就像它更新指令圖像。
Template HTML
< img ng-src='{{tempimagefilepath}}/>
AngularJS Code
photoalbumServ.rotate_photo(post).then(function(data) {
//after server modifies photo
$scope.$apply(function() {
$scope.tempimagefilepath = $scope.baseurl + "user_images/user_43/temp/123-temp.jpg";
});
});
像其他人說的那樣使用ng-src。 但重要的是要參考你的控制器
<div ng-controller = "controller">
<img ng-src="{{tempimagefilepath}}" />
</div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.