Every time I select a value for the first time, the ng-repeat array updates table data, but it doesn't update the table data just once

I am facing an issue with updating the table view based on select option in my project. The problem is that the table view updates only once when I select the option for the first time, but it doesn't update when I choose the option again. I'm having trouble identifying what might be causing this issue. Can someone please assist me in resolving this?

Below is the code snippet from app.js:

$scope.User = {};

    $scope.arr = [];
    $scope.loaddata = function(User) {
    $scope.User.site = layouts;
    AllServices.teamAllDataFunction1(User)
            .then(function(response) {
    $scope.User.data=response.data;
    });

    };
    $scope.getdatalayoutwise = function(User) {
            var total = 0;
            var total1 = 0;
            for (var i = 0; i < ($scope.User.data).length; i++) {

                if($scope.User.data[i].Layout == $scope.User.selectedSite) {
                    total += parseInt($scope.User.data[i].dp_inst_pending);
                    $scope.arr.push($scope.User.data[i]);
                }
            }

            for (var j = 0; j < ($scope.User.data1).length; j++) {
                if($scope.User.data1[j].Layout == $scope.User.selectedSite) {
                    total1 += parseInt($scope.User.data1[j].DP_Inst_Pending);
                }
            }

            $scope.User.teamTotal = total;
            $scope.User.personalTotal = total1;

            $scope.data = [$scope.User.teamTotal, $scope.User.personalTotal];
            $scope.totamnt =  parseInt($scope.User.personalTotal) + parseInt($scope.User.teamTotal);
            $scope.User.totalamount = $filter('translate')('totalpending') + ": " + $filter('currency')($scope.totamnt, "");
            $scope.User.data = $scope.arr;
        };

Here is a portion of the HTML code:

<select name="site" ng-model="User.selectedSite" ng-change="getdatalayoutwise(User)">
                    <option value="">--{{'selectsite_message' | translate}}--</option>
                    <option ng-repeat= "option in User.site" value="{{option.Layout}}">{{option.Layout}}</option>
                </select>

<table ng-table>
                <tr>
                    <th>advisor_name</th>
                    <th>totalpending</th>

                </tr>

                <tr ng-repeat="data in User.data | filter : {Layout: User.selectedSite}: true" ng-if="data.dp_inst_pending">
                    <td class="ui-helper-center"><a ng-click="advisorDetails($index, data, User)">{{data.AdvisorName}}</a></td>
                    <td>{{data.dp_inst_pending | currency:"&#8377;":0}}</td>   
                </tr>
            </table>

Answer №1

It is important to utilize $scope.$apply() in this scenario:

$scope.getdatalayoutwise = function(User) {

   $scope.$apply(function () {
      var total = 0;
      var total1 = 0;
      for (var i = 0; i < ($scope.User.data).length; i++) {

          if($scope.User.data[i].Layout == $scope.User.selectedSite) {
             total += parseInt($scope.User.data[i].dp_inst_pending);
             $scope.arr.push($scope.User.data[i]);
          }
      }
      ...
   }); 
}

Answer №2

Revise your function like this

$scope.loadData = function(User) {
    $scope.User.data = [];
    $scope.User.site = layouts;
    AllServices.retrieveAllDetails(User)
            .then(function(response) {
    $scope.User.data=response.data;
});

Include an additional ng-if

<table ng-table ng-if="User.data.length">
    <tr>
        <th>advisor_name</th>
        <th>totalpending</th>
    </tr>
    <tr ng-repeat="data in User.data | filter : {Layout: User.selectedSite}: true" ng-if="data.dp_inst_pending">
        <td class="ui-helper-center"><a ng-click="details($index, data, User)">{{data.AdvisorName}}</a></td>
        <td>{{data.dp_inst_pending | currency:"&#8377;":0}}</td>   
     </tr>
</table>

Answer №3

Insert the following code snippet at the beginning of the getdatalayoutwise () function:

$scope.arr = [];

Answer №4

Managed to solve the issue by implementing the following steps

$scope.ensureSafeApply = function(callback) {
        var currentPhase = this.$root.$$phase;
        if(currentPhase == '$apply' || currentPhase == '$digest') {
            if(callback && (typeof(callback) === 'function')) {
                callback();
            }
        } else {
            this.$apply(callback);
        }
    };

$scope.fetchDataByLayout = function(User) {
var totalSum = 0;
      var totalSum1 = 0;
      for (var index = 0; index < ($scope.User.data).length; index++) {

          if($scope.User.data[index].Layout == $scope.User.selectedSite) {
             totalSum += parseInt($scope.User.data[index].dp_inst_pending);
             $scope.arrList.push($scope.User.data[index]);
          }
      }
      ...
$scope.ensureSafeApply(function() {
$scope.User.data = $scope.arrList;
   }); 
};

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

Monitoring changes to an array of objects in AngularJS within a Select tag using the ng-repeat directive

My goal is to monitor select tags using ng-repeat and disable the save button. My current setup includes: Initially, I will have three select boxes with values. The user must select at least one value from these boxes to enable the Save button. The u ...

Minify causes AngularJs to error out

When I minify my AngularJS code, I encounter an error: The module 'app' failed to instantiate due to: Error: [$injector:unpr] Unknown provider: t The code only works when using gulp without the --production flag. //All dependencies used below ...

Utilize Angular's grep or filter method to retrieve an object based on its unique identifier

I have a collection of Category objects stored as a JSON array in vm.data within my controller for an Angular repeater. Now, I want to access the SubCats within each category by using the 'Category' field in each SubCat. Below is a generic funct ...

AngularJS does not update values properly if there is a style applied to the parent container

I'm struggling to find the best approach to handle this situation. This is how my AngularJS code looks: <span class="something" ng-hide="onsomecondition"> {{value}} </span> .something{ text-align:left; padding:10px;} Issue: The value ...

Angular login/signup modal/dialog component for seamless user authentication

Currently, I am working on adding a login/signin dialog to my app similar to the one used by Medium. After doing extensive research online, I have decided to use the $modal from angular ui-bootstrap for this. Can anyone please recommend a tutorial that wil ...

Establishing bidirectional communication with a service property in an Angular application

A service called settings is being used to store application-wide settings as public variables. The goal is to allow users to modify these settings through different input elements, which requires establishing a "two-way binding" between a property of the ...

Check for pattern using JavaScript regular expression

Utilizing ng-pattern to validate a regular expression. The pattern must include 3 letters and 2 numbers in a group. For example: G-31SSD or G-EEE43 Currently, the pattern only matches the second example. ng-model="newGroup.groupCode" ng-pattern="/^&bso ...

When using Lockdown.js with NPM, I encounter a blank file being returned

When using Lockdown.js for NPM, I encountered an issue where the command to generate the lockdown file resulted in an empty file. Here are the links for the dependencies: NPM lockdown git Here is a snippet from my package.json: { "name": "nw", "pri ...

Table order is requested, but the index fails to comply

I am facing an issue with sorting and deleting data from a JSON table. Even after sorting the columns, clicking "Delete" removes the wrong entry because the $index is not updated properly. Here is the JavaScript code I am using: $scope.friends = ...

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 ...

Attempting to determine the smallest and largest dimensions of two values using CSS3

Trying to make sure the image on my phone adjusts its size based on orientation, I attempted using Ionic4. When in landscape mode, I want it to adapt according to height instead of width. Essentially, I need it to use the minimum size and also require the ...

AngularJS modules are not loading dependencies such as constants or controllers

While searching for the reason why a properly defined factory is not loading, I came across this question. This led me to contemplate on the concept of services being "defined in an angular module". Consider this example: angular.module('d3', ...

Unlock the potential of Angular $http by leveraging TypeScript generics in your web development projects

I have been attempting to implement a generic promise return in my code: public getUserData: () => ng.IPromise <string> = () => { var promise = this.makeRequest<string>('http://someurl.com',null) .then((resp ...

Injecting controllers and classes dynamically using AngularJS

I'm currently working on a dynamic widgets list where each widget is defined by its html, class, controller, and name. Some of these parameters may be empty based on the type of widget. These widgets are then loaded dynamically into <li> element ...

The ERR_ASSERTION error is thrown because the catch clause variable is not an instance of the Error class

For some reason, I am unable to set up the authentication, firestore, and cloud storage in my project as I keep getting this error message: [error] AssertionError [ERR_ASSERTION]: catch clause variable is not an Error instance at assertIsError (C:\Us ...

What Are the Possible Use Cases for Template Engine in Angular 2?

For the development of a large single page application (SPA) with Angular 2.0, I have decided to utilize a template engine like JADE/PUG in order to enhance clarity and clean up the code. My goal is to achieve optimal performance for the application. Th ...

Configuring .htaccess on Heroku for an AngularJS application

I have recently deployed an AngularJS application using the lineman-angular template on Heroku. The app is working fine, but I am facing an issue with the "Page not found" error when I refresh the page with HTML5 mode enabled. After looking into a solutio ...

Tips for incorporating ng-if logic within a controller

Considering transferring my ng-if logic to the controller. In this scenario, the condition is in HTML. <div data-ng-if="transfer.fromAccount.number !== '12538855' && transfer.status === 'Completed'" > </div> ...

The function call with Ajax failed due to an error: TypeError - this.X is not a function

I am encountering an issue when trying to invoke the successLogin() function from within an Ajax code block using Typescript in an Ionic v3 project. The error message "this.successLogin() is not a function" keeps popping up. Can anyone provide guidance on ...

Is your pagination feeling a bit sluggish?

I have been working on a basic table application that showcases dummy data with columns such as name, number, date, and more. Users have the ability to sort the table by columns and navigate through paginated pages. However, I have encountered an issue wh ...