Unable to update the scope upon $emit in the component

In my AngularJS component, I have a value stored in the scope that provides a URL to an <img> element in the view. Whenever a user changes the image, the controller emits a change using $rootScope.$emit, causing the URL value to update. Ideally, the view should also update to display the newly uploaded image:

angular.module('ppApp').component('mainnav', {
    templateUrl: 'app/templates/nav/nav.main-nav.tpl.htm',
    controller: ['$scope', function($scope){

        vm.avatarimage = '../p3sweb/avatarImage';

        $rootScope.$on('refreshAvatar', function(){
           console.log('change avatar')
           vm.avatarimage = '../p3sweb/avatarImage';
        })

    }]
})

//Controller
$rootScope.$emit('refreshAvatar',function(){ //value refreshAvatar emitted when they have loaded new image

})

//view
<img data-ng-src="{{$ctrl.avatarimage}}" alt="users profile pic" class="profile-pic-radius">

Although the emission is detected and the message 'change avatar' is logged, the image does not update unless I manually refresh the page.

Query

How can I trigger a refresh specifically for the component so that it updates the scope and displays the newly uploaded image?

Answer №1

The issue does not lie with Angular.js itself, but with the need for a workaround to update your image as the img tag does not refresh until its source is altered.

One solution is to append a timestamp at the end of the image source URI.

...
    $rootScope.$on('refreshAvatar', function(){
        console.log('updating avatar')
        // SOLUTION HERE!!!
        var timestamp = new Date().getTime();
        vm.avatarimage = '../p3sweb/avatarImage' + '?' + timestamp;
    })
...

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

Instructions for setting attributes on the ngForm object within a component class

My form data is represented as a JSON string using JSON.stringify(form.value) and it currently looks like this: "body":{ "panNo":"IRFPP1993A", "ackNo":"123456789" } I would like to modify the output to include an additional value, making it look like thi ...

The binding in webstorm for AngularJS is not displaying correctly

Recently, I've started learning angularJS but I'm struggling with a particular issue: Everything works perfectly when using the official phonecat tutorial file. However, when I try to create my own project, the data binding doesn't display ...

collaborative data interchange in angularjs controllers

When it comes to managing shared state between controllers, I often struggle to find the best approach among the many options recommended on forums like Stack Overflow. To help clarify my thoughts, I've created a simple diagram outlining my basic idea ...

Encountering an error "[$rootScope:inprog]" while using Angular select with ngModel

I'm still learning my way around Angular, but I have a basic understanding. Right now, I'm working on assigning access points to a building using a <select> element. I've created a simple controller for this task, but it's not fun ...

The view displays a true boolean value, while the controller is returning a false boolean value in

Within the parent scope (the external one that wraps the entire webapp), a boolean variable is defined to check if the user is logged in. $localForage.getItem('authorization') .then(function(authData) { if(authData) { ...

Applying Angular to Add a CSS Class

I am working with an Angular controller and have the following model on the scope: $scope.model = { subscriber: { email: '', name: '' }, notice: { text: '', type: '' } } My goal is to display a P tag when notic ...

A guide on converting character objects to strings

Presented below is an array of characters: Resource {0: "-", 1: "-", 2: "-", 3: "-", 4: "-", 5: "B", 6: "E", 7: "G", 8: "I", 9: "N", 10: " ", 11: "C", 12: "E", 13: "R", 14: "T", 15: "I", .... } I am looking to convert it into the following format: --- ...

The functionality of Directive hinges on the use of a template

I am exploring a more web-component approach to using Angular. As part of this, I have developed an http-request directive with url and response attributes. The implementation is successful, but I find that my directive relies on a template unnecessarily. ...

Is it possible to execute a controller function only when the textarea has completely loaded?

My current setup includes a textarea as shown below: <textarea rows="3" maxlength="144" ng-maxlength="144" type="text" name="testPost" id="testPost_{{item.id}}" ng-init="focusText('testPost', item.id)" ng-model=" ...

Display a variety of HTML pages using the md-tab component

I'm currently learning about angular material and I have a question regarding how to display different HTML files for each md-tab. For instance, I want to set up 3 tabs: the first one should show catalog.html, the second should display manage.html, an ...

React Typescript: The specified argument type cannot be assigned to the parameter type

Creating a Check Box Button React component has resulted in an error related to setRSelected(1) and setRSelected(2)... const [cSelected, setCSelected] = useState([]); const [rSelected, setRSelected] = useState(); const onCheckboxBtnClick = (selected ...

AngularJS Gallery Showcase

Trying to showcase a collection of videos in a modal using angular.js, I decided to implement the solution from . However, I encountered difficulty in integrating my scope variables into the "html5gallery" class. <div class="html5gallery" data-skin="ho ...

Creating a dual-column layout using ng-repeat

My issue involves creating a 2-column table using looping through a list like this: <style> .columns2 { columns: 2; } </style> <tr> <td class="columns2"> <ul> <li ...

Exploring the World of Metaprogramming with AngularJS Filters

Can we generate filters dynamically in Angular? Below are some basic filters that extract specific properties from an array of objects. module.filter("firstAndLastName", function() { return function(input) { return input.map(function(obj) { ...

Obtain scope in AngularJS using object ID

Is it possible to retrieve the specific scope of an object by accessing it through an ID? I am currently using angular ui tree for a navigation menu. However, I face an issue where after adding a subitem and saving the navigation into a mysql database, th ...

What is the significance of the expression $location.path() equal to '/a' in Angular?

I am currently delving into AngularJs for the first time and I have been studying the Angular documentation in order to grasp its concepts. While going through it, I came across this piece of code: $location.path() == '/a'. However, I am struggli ...

AngularJS enables box to smoothly slide up and down when hovered over

I am attempting to create a div that will overlay an image on hover with a slide up and slide down effect. Can anyone provide guidance on how to achieve this without relying on jQuery? I would prefer to utilize only AngularJS in my application. Here is a ...

Angular JS: Extracting the header from a CSV file

Just getting started with angular JS and I have a question. I need to take a CSV file from the user as input and then send it to the controller when they click submit. <button class="btn btn-primary" type="submit" ng-click="Input(File)">Submit</ ...

Issue arises when Protractor is unable to compare a variable with a web element due to unresolved promises

My strategy for this examination was to extract the inner text of an element, modify it, and then verify that the change had taken place by comparing the element with the variable. var fixedValue = element(by.xpath('/html/body/section/div/section/sec ...

How can I show only the final four digits of an input field using Angular Material and AngularJS?

As a newcomer to Angular Material and Angular JS, I am striving to create an md-input field that displays only the last 4 digits in a masked format, such as "********1234". While my experience is currently limited to using md-input password fields where ...