I encountered a similar issue where I had implemented a custom <user-picture>
directive allowing users to change their profile picture on the settings page. The picture source was fetched from an API using a token appended to the URL. After successfully updating the picture in the database, I needed to ensure that every instance of the directive reflected this change by updating the
ng-src="{{mainCtrl.picture.src}}"
file.
The directive code is as follows:
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;
}]);
I dynamically bind the image source using
ng-src="url file address string"
from mainCtrl. Upon changing the picture in the database, I update the value of $scope.mainCtrl.picture.src with the same URL + token while also adding an additional
&rand
parameter to the URL. This results in a modified URL structure like this:
http://<domain>/<serverApi>/user/getPictureAsStream?token=65145d12-f033-41f1-b101-9ed846352284&rand=0.6513215699
, where the last
&rand=0.6513215699
informs the browser to fetch a new file with each request, even if it's located at the same location. The server disregards this extra parameter, ensuring the updated picture is displayed in the directive.