What is the best way to attach new array values to a directive?

I'm receiving messages from a server using socket.io and adding them to the $scope.event array each time a message is received. How can I update the directive isolated scope's message value when a message is received in the controller? It doesn't seem to be working with the code below.

directive.js

angular.module("App").directive('progressBarCustom',function () {
    return {
        restrict: 'E',
        scope:{
            message: "=",
            fileSize: "=",
        },
        templateUrl: '/view/partials/progressbar.html',
        controller: "StCtrl",
        link: function(scope, el, attrs) {
            var data = scope.message;
    }
});

main.html

<ul style="list-style: none;">
                            <li ng-repeat="message in event track by $index" ng-class="{lastItem: $last}"><span><strong>Log:</strong></span><span>{{message}}</span></li>
                        </ul>

ctrl.js

socket.on('ditConsumer',function (data) {
        $scope.event.push(data);
}

$scope.event = ["lorem ipsum","lorem ipsum"];

template.html

<progress-bar-custom ng-show="progressBarFlag" message="event"  file-size="selectedFileSize"></progress-bar-custom>

Answer №1

Although I have not previously utilized socket.io, it appears that the callback is running independently from Angular's control. Therefore, in order to notify Angular of any changes, you should incorporate a $scope.$apply.

Consider implementing the following solution:

socket.on('ditConsumer',function (data) {
  $scope.$apply(function() {
    $scope.event.push(data);
  });
}

According to the documentation:

$apply() is essential for executing an expression within angular from external sources. This could be triggered by browser DOM events, setTimeout, XHR requests or third party libraries. Since we are interacting with the angular framework externally, it is imperative to follow the correct scope lifecycle and exception handling procedures, as well as execute necessary watches.

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

Evaluating $http Functionality with Jasmine Testing

I have been tasked with simulating an ajax call using jasmine for testing purposes. Below is the code snippet I am working on: var httpBackend; var http; beforeEach(inject(function ($injector) { $httpBackend = $injector.get('$httpBackend') ...

Alter the div's HTML content once the Ajax operation is completed

I have a div element that looks like this: <div class="progress" id="progress-bar"></div> I am using the following JavaScript code along with an ajax call to retrieve some data. The data returned is 0, however, the content is not being added ...

Show a modal when the axios request is finished

EDIT: After some exploration, I've shared the solution I found in case it helps others facing a similar issue. I'm currently working on building a reusable Bootstrap 5 modal child component within Vue3. The goal is to pass an ID as a prop from t ...

The click event will not be triggered if the element is removed by my blur event

My dropdown list is dynamic, with clickable items that trigger actions when clicked. Upon focus, the list displays suggested items When blurred, the list clears its contents The issue arises when blur/focusout events are triggered, causing my element to ...

Unable to successfully rename an uploaded file utilizing Multer in the Express.js environment

While working on uploading a file from an HTML form using Express.js and Multer, I have successfully saved the file to a specific location (a folder named uploads). However, I am looking to rename the file during the upload process because Multer assigns ...

Dayjs is failing to retrieve the current system time

Hey everyone, I'm facing an issue with using Dayjs() and format to retrieve the current time in a specific format while running my Cypress tests. Despite using the correct code, I keep getting an old timestamp as the output: const presentDateTime = da ...

Obtain the inner DIV's ID by clicking on it and using JavaScript

I am trying to extract the ID of the inner DIV using JavaScript. You can view the fiddle http://jsfiddle.net/5yn2hLv9/8/. When I click on First Tab/Second Tab..., the ID of the tab should be fetched in the JavaScript function getInnerDivId(). Any suggestio ...

Fade in elements individually with the jQuery Waypoints plugin

I am currently using the waypoints jQuery plugin and it is functioning perfectly when fading in on scroll. However, I am facing an issue with making the blocks fade in individually one after the other. Here is the snippet of my jQuery code: $('.hbloc ...

Guide for implementing Ajax-based login functionality using Spring Security in a Grails and AngularJS application

I am currently working on developing a user form that utilizes Ajax requests to log in to the server. Within my Angular app, the POST function is structured like this: $http({ method: 'POST', url: '/j_spring_security_check', ...

Retrieving data from Immediately Invoked Function Expressions

I've been working with a closure that looks like this: var Container = (function () { var variable; var changeVariable = function () { variable = 5; }; return { variable: variable, changeVariable: changeVariable }; ...

Restrict the quantity of file uploads in plupload

My client is currently using an outdated version of ClassiPress, and I came across a GitHub repository for the theme. However, the version my client has is even older than what is available on GitHub. The website is running on the latest WordPress version ...

JavaScript - Sending Form Data with Local Time

I want to automatically submit a form at a specific time of day The form should be submitted every day at "15:30:00" Here is the JavaScript code I have written: <script type="text/javascript> function initClock() { var now = new Date(); var h ...

Creating a user-friendly form with validation in a Vue application using Vuetify.js

I am in the process of incorporating a contact form with basic validation on a Vue.js website using an example from Vuetify.js. Being new to this, I'm unsure about how to implement it within a Vue component. My goal is to have simple client-side form ...

Connect JSON data to a table using knockoutjs

Looking for help on binding my JSON object with knockoutjs. Here's the JSON data: "{\"Sport\":[{\"Name\":\"nana\",\"Description\":\"lmkmsdqd\",\"EndDate\":\"2012-07-22T00:00:00\"} ...

Troubleshooting issue: pesky popper.js error arises when integrating Bootstrap 4 into the Require

As I integrate Bootstrap 4 into my RequireJS configuration for my application, a warning arises: An error occurred while loading the resource from: “”. accompanied by this error message: Error: Script error for "popper.js", required by: bootst ...

Transferring properties from React Router to child components on the server side

For my Isomorphic app using React, react-router v3, and material-ui, it's crucial to pass the client's user agent to the theme for server-side rendering. This is necessary for MUI to properly prefix inline styles. Initially, the root component o ...

What methods can be employed to reduce additional background tasks when altering a state in a React component?

Trying out Code I experimented with creating a React exercise code that showcases a bus and its seats. Reserved seats are marked in red and cannot be selected, while the remaining seats can be chosen by clicking on them and selecting a gender from a popup ...

Is there a way to ensure a dialog box is positioned in the center of the window?

After adjusting the dimensions of my jQuery UI dialog box with the following code: height: $(window).height(), width: $(window).width(), I noticed that it is no longer centered on the window. Do you have any suggestions on how I can recenter it? ...

Converting an array into an object with Express JS: A comprehensive guide

Take a look at my user model to understand the structure of my database. var userSchema = new Schema({ firstName: {type: String, required: true, trim: true}, lastName: {type: String, required: true, trim: true}, address: { street: {type: String, requi ...

An unforeseen SyntaxError has occurred: Unexpected token : found in the JSON data returned from an AngularJS API request

Currently, I'm encountering an error that leads me to a JSON response when clicking on the provided link: {"link-canonical":"https:\/\/myanimelist.net\/anime\/1\/Cowboy_Bebop",.....} My issue arises while making a get reques ...