Reputation: 7627
I'm trying to reload an image from my webserver every n seconds. The code below drags the new picture, but it doesn't replace the old one in the client. Where is my mistake?
<div ng-app="refresh-div" ng-controller="refresh_control">
<img ng-src="{{imageUrl}}" />
</div>
<script>
var app = angular.module('refresh-div', [])
.controller('refresh_control', function ($scope, $http, $timeout) {
$scope.imageURL = 'assets/now.png?_ts=' + new Date().getTime();
$scope.getData = function () {
$http.get($scope.imageURL, {
cache: false
}).success(function (data, status, headers, config) {
$scope.image = data;
$scope.imageUrl = "http://mywebsite/assets/now.png";
});
};
$scope.intervalFunction = function () {
$timeout(function () {
$scope.getData();
$scope.intervalFunction();
}, 1500)
};
$scope.intervalFunction();
});
</script>
Upvotes: 4
Views: 14515
Reputation: 7627
Fixed the problem, the issue was that $scope.imageURL = 'http://mywebsite/assets/now.png?_ts=' + new Date().getTime(); was missing from the success function. Basically, I needed to updated the url of the image. I'm not sure if it is the best solution, but it is working for my requirements.
<div ng-app="refresh-div" ng-controller="refresh_control">
<img ng-src="{{imageURL}}" />
</div>
<script>
var app = angular.module('refresh-div', [])
.controller('refresh_control', function ($scope, $http, $timeout) {
$scope.imageURL = 'http://mywebsite/assets/now.png?_ts=' + new Date().getTime();
$scope.getImage = function () {
$http.get($scope.imageURL, {
cache: false
}).success(function (data, status, headers, config) {
$scope.imageURL = 'http://mywebsite/assets/now.png?_ts=' + new Date().getTime();
});
};
$scope.intervalFunction = function () {
$timeout(function () {
$scope.getImage();
$scope.intervalFunction();
}, 1500)
};
$scope.intervalFunction();
});
</script>
Upvotes: 3
Reputation: 1209
a) <img ng-src="{{imageUrl}}" />
- it force Angular.js watch the changes of the value of $scope.imageUrl. When this value changed Angular update image.
b)
$scope.getData = function () {
$http.get($scope.imageURL, {
cache: false
})
.success(function (data, status, headers, config) {
$scope.image = data;
$scope.imageUrl = "http://mywebsite/assets/now.png"; // <== this line
});
This line $scope.imageUrl = "http://mywebsite/assets/now.png";
always set the same value for $scope.imageUrl
. In result there is no updates.
Maybe this code
$scope.intervalFunction = function () {
$timeout(function () {
$scope.imageURL = 'assets/now.png?_ts=' + new Date().getTime();
}, 1500);
};
makes more sense?
Upvotes: 3