Launching the forEach function within an ng-repeat loop was it can be done by

I need to implement a function within the ng-repeat that will convert the value of Qprogress object in my JSON into a percentage. I already have the function written, but I am struggling with how to trigger it. I attempted to use a forEach loop inside the scope and then utilize the scope as the ng-model for the element I want to modify, but this approach is not yielding desired results. Below is the HTML structure:

<tr ng-repeat="item in clients" progressCalc>
    <td>
        <a href="#/details/{{clients.indexOf(item)}}" title="Link to {{item.FirstName}} {{item.LastName}}" class="oly-open">{{item.FirstName}} {{item.LastName}}</a>
    </td>
    <td ng-hide="item.Progress == 'In Progress'" ng-class="{ 'status-success': item.Progress == 'Questionnaire Completed', 'status-error': item.Progress == 'Unsent'}">
        {{item.Progress}}
    </td>
    <td ng-if="item.Progress == 'In Progress'" ng-model="progressCalc" class="status-info percent">
        {{item.Qprogress}}
    </td>
    <td width="10%">
        <a href="#/reports/" title{{$index + 1}}="Reports" ng-show="{{item.Progress == 'Questionnaire Completed'}}">
            <span class="stat-icon-report"></span>
        </a>
        <a href="#/sends/{{$index + 1}}" title="Alert" ng-show="{{item.Progress == 'Unsent'}}">
            <span class="stat-icon-bullhorn"></span>
        </a>
        <a href="#/progress/{{$index + 1}}" title="In Progress" ng-show="{{item.Progress == 'In Progress'}}">
            <span class="stat-icon-phone"></span>
        </a>
    </td>
</tr>

Additionally, here is the corresponding JavaScript code:

myApp.controller('clientStatus', ['$scope', '$http', function($scope, $http) {
    $http.get('assets/js/lib/angular/clientList.json').success(function(data) {
        $scope.clients = data;

        $scope.progressCalc = function() {
            angular.forEach(function(item) {
                var m = 0.26664;
                var s = 0.26664;
                var i = 0.694375;
                var t = item.Qprogress;
                t = t.replace(/m/g,'');
                t = t.replace(/s/g,'');
                t = t.replace(/i/g,'');
                var ta = t.split("/");
                var tTotal = (ta[0] * m) + (ta[1] * s) + (ta[2] * i);
                tTotal = Math.round(tTotal);
                $('.percent').append(tTotal + '%');
            });
        };
    });
}]);

Lastly, here's a snippet of the JSON data format:

"FirstName": "Bill",
"LastName": "Johnson",
"Company": "Texas Instruments",
"CompanyId": "2345672",
"ClientId": "EFTGE6",
"Title": "CIO",
"Phone": "555-555-5555",
"ClientSystemStatus": "Active",
"CreationDate": "06/03/2015, 10:35:59 am",
"Progress": "In Progress",
"Qprogress": "m125/s40/i0",
"Email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e1838b8e89928e8fa19588cf828e8c">[email protected]</a>"

Thank you!

Answer №1

Uncertain of the specific calculation you require, but it seems that the forEach function may not be necessary. I made some adjustments and corrections which you can review below.

Controller:

$http.get('assets/js/lib/angular/clientList.json').success(function(data) {
    $scope.clients = data;
});

$scope.progressCalc = function(item) {
    var m = 0.26664;
    var s = 0.26664;
    var i = 0.694375;
    var t = item.Qprogress;
    t = t.replace(/m/g,'');
    t = t.replace(/s/g,'');
    t = t.replace(/i/g,'');
    var ta = t.split("/");
    var tTotal = (ta[0] * m) + (ta[1] * s) + (ta[2] * i);
    tTotal = Math.round(tTotal);
    return tTotal + '%';
};

HTML:

Note the first line where I removed an incorrect directive call for progressCalc. Furthermore, as an example, I demonstrate method calling by using progressCalc to display the result.

<tr ng-repeat="item in clients">
    <td>
        <a href="#/details/{{clients.indexOf(item)}}" title="Link to {{item.FirstName}} {{item.LastName}}" class="oly-open">{{item.FirstName}} {{item.LastName}}</a>
    </td>
    <td ng-hide="item.Progress == 'In Progress'" ng-class="{ 'status-success': item.Progress == 'Questionnaire Completed', 'status-error': item.Progress == 'Unsent'}">
        {{item.Progress}}
    </td>
    <td ng-if="item.Progress == 'In Progress'" class="status-info percent">
        {{item.Qprogress}} {{progressCalc(item)}}
    </td>
    <td width="10%">
        <a href="#/reports/" title{{$index + 1}}="Reports" ng-show="{{item.Progress == 'Questionnaire Completed'}}">
            <span class="stat-icon-report"></span>
        </a>
        <a href="#/sends/{{$index + 1}}" title="Alert" ng-show="{{item.Progress == 'Unsent'}}">
            <span class="stat-icon-bullhorn"></span>
        </a>
        <a href="#/progress/{{$index + 1}}" title="In Progress" ng-show="{{item.Progress == 'In Progress'}}">
            <span class="stat-icon-phone"></span>
        </a>
    </td>
</tr>

I have not tested this solution, but it should work or provide some guidance!

Answer №2

When approaching this scenario, especially if the calculation is only required once per item, my suggestion would be to execute the method from your controller as a callback function.

$http.get('assets/js/lib/angular/clientList.json').success(function (data) {
    $scope.clients = data;
    $scope.clients.forEach(function(client) {
         //perform your calculations here.
    });
});

If executing the code directly from the html is necessary, then I recommend referring to the solution suggested by @manzapanza.

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

Trigger specific scripts again after loading jQuery AJAX

Is there a way to make specific scripts re-run after an AJAX load is completed? ...

Enumerating items in a JSON dataset

I am facing an issue with my JSON data structure: var data = { "conv0": { "id":"d647ed7a5f254462af0a7dc05c75817e", "channelId":"emulator", "user": { "id":"2c1c7fa3", "name":"User1" }, "co ...

What is the method for utilizing a filter to extract the specific value from the elements within an array of double objects?

I am facing an issue with my code where I have an array called pick containing objects and another object named diaryItem. My goal is to extract only the object with the name 'wormColor' from the diaryItem object. Unfortunately, when I tried run ...

Issue with IE due to jQuery/JavaScript conflict

After selecting one of the two radio buttons, I want to increment the total by $10. If the other option is selected, I want to revert back to the original total price. The jQuery function I am currently using is as follows: function check_ceu() { var ...

Creating a HTML5 canvas animation of an emoticon winking to add a fun touch to your

Currently, I am facing a challenge in animating an emoticon that was initially sketched on canvas. While following a tutorial to implement draw and clear animations using frames, I haven't been able to achieve the desired outcome. With 6 frames of the ...

Send a POST request with an NSDictionary set in the HTTPBody

I need to make a web service call using the POST method. I have to send a dictionary along with a URL to my web service. Below are the parameters required for my web service: ConversationMessage { authorUserId (string, optional), subject (st ...

The amalgamation of geometries using BufferGeometryUtils results in variations from the original model

I have encountered an issue when attempting to merge GLB model geometries with three.js using BufferGeometryUtils.mergeBufferGeometries. The new merged geometries do not always align perfectly with the original model. Furthermore, some of the geometries e ...

Top solution for maintaining smooth navigation across web pages

As I dive into the world of web development, I find myself intrigued by the idea of reusing navigation and banners across multiple web pages. However, despite my research efforts, I have yet to come across a definitive answer. My objective is simple: The ...

Steps to retrieve an array from AJAX request and save it to a JavaScript variable

How can I retrieve the 'this.responseText' array from this function and assign it to a variable named 'teacherIDList'? Any suggestions? var xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function() { if (this.readySt ...

How can I retrieve the URL of the previous page from the history object in all browsers?

Can we retrieve the URL of the previous page from the history object? I've seen references to history.previous, but it appears to be either undefined or protected based on my observations. ...

Troubleshooting jQuery Dropdown Menu Animation Bugs

Take a look at this interesting fiddle: https://jsfiddle.net/willbeeler/tfm8ohmw/ HTML: <a href="#" class="roll-btn">Press me! Roll me down and up again!</a> <ul class="roll-btns"> <li><a href="#" class="control animated noshow ...

Encountering a connection error when trying to access a Google spreadsheet within a Next.js application

I am currently exploring Next.js and attempting to utilize Google Sheets as a database for my project. Although my application is functioning correctly, there is still an error message displaying that says "not forgot to setup environment variable". I have ...

Troubleshooting a glitch with passing a variable to a PHP script using AJAX

Explanation of the page functionality: When the quiz php page loads, a user can create a score using a function in quiz.js. This score is then stored in a variable score within quiz.js Once the score is generated, the user must click a button to move on ...

Tips for effectively implementing a curried selector function with the useSelector hook in react-redux

In my project using react-redux with hooks, I encountered a situation where I needed a selector that takes a parameter which is not passed as a prop. Upon checking the documentation, it mentioned: The selector function does not receive an ownProps argum ...

Exploring the Battle between LocalStorage and Redis for Front-end and NodeJS Development

Which approach is better for storing common user information like username and image: using localStorage or implementing Redis caching with NodeJs on the front-end? ...

An Effective Solution for Resolving the 'Use JsonReader.setLenient(true) to Accept Invalid JSON at Line 1 Column 1 Path $' Issue in Android Studio

I'm facing an issue while attempting to send a POST request to an API. The error message I receive is: To fix the problem, you can use JsonReader.setLenient(true) method in order to accept malformed JSON at line 1 column 1 path $. Is there anyone ...

When the button is clicked, request the total count of elements in the array

Is there a way to log the index of an array element when clicked? I have a large array with over 100 elements: var cubesmixed = []; var cubes; for(var i = 0; i < 143; i++) { cubes = paper.rect(Math.floor(Math.random()*2000), Math.floor(Math.random ...

Error: Uncaught TypeError - Unable to assign a value to the 'status' property

Hello everyone, I am currently facing an issue with validating the response from my server using Axios in VueJS. axios.post('/login', { email: this.email, password: this.password }).then(response => { if (response.status == 200) { $ ...

Node.js server continues running after attempting to stop with ctrl + C following starting the server using the command "npm start"

Whenever I initiate my server by typing node app.js in the command line on Git Bash, I can stop it simply by using ctrl + C. In my package.json file, I have configured a start script that allows me to use the command npm start to kickstart the server: "s ...

How can I utilize React to pull information from the Google Taxonomy API?

Seeking assistance with React development, as I am a beginner and looking to retrieve data from this URL and organize it into a tree structure. I not only want to fetch the data but also display it in a tree format. My current code successfully retrieves t ...