update angularjs image source based on model updates

I need assistance with showing a server-side image rotation change on my webpage. How can I achieve this?

Is using $scope.$apply() the correct approach? Whenever I utilize it, I encounter the error message "digest cycle in progress".

Here is a snippet of template.html:

<img src='{{tempimagefilepath}}'> <!--image-->

And here is a portion from controller.js:

photoalbumServ.rotate_photo(post).then(function(data) {
  //once server modifies photo
    $scope.tempimagefilepath = $scope.baseurl + "user_images/user_43/temp/123-temp.jpg";
     $scope.$apply();
});

Thank you for your help.

Solution:

To display the updated image, I had to modify the scope value of {{tempimagefilepath}} so that the image changes accordingly. This involved renaming the file on the server each time I rotated the image.

Answer №1

There are a couple of important points to consider. First, it is recommended to utilize ng-src instead of src in order to prevent the image from being loaded by your clients before Angular has finished evaluating the expression.

Secondly, when using $apply(), make sure to pass it a function callback that will implement the necessary scope changes. Here's an example:

photoService.updateImage(post).then(function(response) {
    // Once the server has made changes to the image
    $scope.$apply(function() {
        $scope.imagePath = $scope.baseUrl + "user_images/user_43/updated/123-updated.jpg"; 
    });
});

Answer №2

It appears that the issue may be related to your browser's cache. You should not have to use $apply().

Here is a potential solution:

var random = (new Date()).toString();
$scope.tempimagefilepath = newUrl + "?cb=" + random;

Answer №3

Consider utilizing ng-src in place of src attribute.

<img ng-src="{{tempimagefilepath}}" />

It appears there may be no requirement for $scope.$apply() in this case.

Answer №4

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.

Answer №5

Sample HTML
 < img src='{{sampleimgpath}}/>

JavaScript Code
imageService.rotate_image(data).then(function(result) {
    // do something after image rotation
    $scope.$apply(function() {
        $scope.sampleimgpath = $scope.baseurl + "images/user_12/sample/456-sample.jpg"; 
    });
});

Answer №6

Don't forget to include the ng-src directive as mentioned before. Make sure to reference your controller properly.

   <div ng-controller = "myController">
     <img ng-src="{{imageURL}}" />
   </div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Retrieve coordinates of the clicked location with RichMarker in the Google Maps JavaScript API v3

I followed the solution provided here for richmarker.js After implementing it, when I use my_rich_marker.addListener('click', function(event) { console.log(event); //undefined } What I am trying to achieve is to access event.latLng of the ...

What is the best way to create a universal root component in next.js for sending requests, no matter the page URL?

Currently, my goal is to send a request to the server whenever the page is refreshed or opened in a new tab. For instance, after hitting F5, I want to trigger a request. However, I do not want to make a request after every routing event. Essentially, upon ...

Is it considered acceptable in React for the value of one state to be determined by another state?

Consider this scenario: state1 tracks the mouseover of clientX and clientY, while state2 retrieves the value from state1 upon clicking. Is this implementation acceptable? const [move,setMove]=useState([]) const [click,setClick]=useState([]) useEffect(() ...

Issue with updating Three.js Mesh position

I have been working on mapping lat/long data to a sphere. I am successfully generating vectors with different positions and setting the cube mesh position accordingly. However, when I merge and display the cubes, it seems like there is only one cube show ...

What is the reason behind allowing JavaScript to perform mathematical operations with a string type number?

let firstNum = 10; let secondNum = "10"; console.log(firstNum * secondNum); // Result: 100 console.log(secondNum * secondNum); // Result: 100 ...

Troubleshooting Problem with Scrolling to the Bottom of a DIV Using J

I've been experimenting with creating a chat box in jQuery that automatically scrolls to the bottom when the page loads. I've tried various methods, but most of them haven't worked as expected. One method I found animates a scroll down, but ...

Tips for increasing the number of inputs within a form using <script> elements

I am currently working on a form within the script tags and I would like to include additional input fields before submitting. However, the submit button seems to be malfunctioning and I suspect that there may be an issue with how I am accessing it in my c ...

What is the process for embedding MUI into a React Integrated Astro platform?

As I delve into learning Astro, my idea is to incorporate MUI's material components like Button and Typography within the Astro components since I have already enabled React integration. astro.config.js import { defineConfig } from 'astro/config ...

What is the method to deactivate all events in React components using refs?

Currently, I am utilizing TreeView from Material-ui along with a text field for searching other items on the screen. Although TreeView and TextField are unrelated components. However, I have encountered an issue where if I click on a TreeView node and the ...

Is your toggleclass button suffering from technical difficulties?

Why am I having trouble toggling the box with the button? I want it to maintain its current functionality and also toggle the box as well. Check out my JS fiddle for reference. Here's my code snippet: $(function timelinetiles() { $('.timeline ...

What is the reason behind Chrome sending two http requests when Firefox only sends one?

Edit: It seems that the issue with the double response is related to a favicon.ico problem in Chrome but not in Firefox. Can anyone shed light on why this inconsistency occurs between the two browsers? Original: Currently, I am delving into learning Expre ...

Using Angular to dynamically display JSON data on an HTML page

I have JSON data that I need to format into an HTML page where each parent becomes the header and its children are displayed under the same parent in the content area. Another parent will follow with its respective children listed below. How can I achiev ...

JavaScript issue: event.target.innerText not preserving line breaks

Within a conteneditable div, I am displaying pre-populated grey text with the data-suggestion attribute. Upon clicking the text: The text color changes to black The data-suggestion attribute is removed from the selected line An input event on the conten ...

JS, Async (library), Express. Issue with response() function not functioning properly within an async context

After completing some asynchronous operations using Async.waterfall([], cb), I attempted to call res(). Unfortunately, it appears that the req/res objects are not accessible in that scope. Instead, I have to call them from my callback function cb. functio ...

Mastering the art of syncing PouchDB with AngularJS

I'm currently using Couch DB to store location data for my cordova ionic app and utilizing PouchDB for data replication. While everything functions correctly, it appears that the initial replication process does not complete before my application prog ...

Angular reactive forms can be customized to include a patched version of the matTime

I have an angular mattimepicker in my project. When trying to use it in a reactive form, I am encountering issues with patching the value to the edit form <h1>Reactive Form</h1> <form [formGroup]="form"> <mat-form-fie ...

Implementing fullCalendar with eventAllow to limit events based on specific DateTime

I am facing a challenge with restricting events to be dropped only before a specific time within each event. When I drop an event before the date, everything works perfectly fine. However, if I try to drop it after the given date, the event disappears. Can ...

Animating the Bookmark Star with CSS: A Step-by-Step Guide

I found this interesting piece of code: let animation = document.getElementById('fave'); animation.addEventListener('click', function() { $(animation).toggleClass('animate'); }); .fave { width: 70px; height: 50px; p ...

Transform Objects Array from AJAX Response into a Distinct JSON Entity

I am encountering a problem with a sample endpoint that is returning [object Object] for JSON data, and I can't figure out why. Mock API Initially, my code was a bit confusing, but fortunately, I found a clearer solution in another answer. functio ...

Outline border for the parent element of the targeted event

How can I add a border outline to the parent div of the selected event.target? // To display our own context menu instead of the default one $(document).on("contextmenu", function(event) { // Skip if the target is a link if ($(event.target).hasClass ...