AngularJS ng-repeat does not refresh when the $scope variable is modified

Hey, I'm a beginner in Angularjs and I'm trying to update the $scope variable based on dropdown list selection. This scope variable is used for ng-repeat in a div.

Here's the HTML code:

<div class="col-md-6" ng-repeat="model in FilteredModels | filter:{ModelText : '!All models'}:true">
          <div class="well">
            <div class="media">
              <div class="media-object small"><i class="pp-car"></i></div>
              <div class="media-body">  
                <div class="text-box">                                      
                  <h3>{{model.ModelText}}</h3><span class="hr-small"></span>
                </div>
                <div class="dashboard-control clearfix">
                  <div class="simple-metric text-left sub-metric">
                    <div class="metric-title">Satisfaction score</div>
                    <div class="metric-number text-red">{{model.SatisfactionAvg | number:2}}</div>
                  </div>
                  <div class="simple-metric text-left sub-metric">
                    <div class="metric-title">Total interviews</div>
                    <div class="metric-number">{{model.TotalInterviews}}</div>
                  </div>
                </div>
                <ul class="list-standard">
                  <li> <a href="" ng-click="openModal($index)" class="text-black trigger-model-interviews">View interviews</a></li>
                </ul>
              </div>
            </div>
          </div>
        </div>

And here's the Angularjs code :

function filtermodelbyId() {
    $scope.FilteredModels = [];

    dataFactory.getModelIdByFilter($scope.region, $scope.subregion).success($scope.handleSuccess).then(function (result) {
        $scope.FilteredModelIds = result.data;
    });

    if ($scope.FilteredModelIds != null && $scope.FilteredModelIds.length > 0) {
        for (var j = $scope.FilteredModelIds.length - 1; j >= 0; j--) {
            for (var i = $scope.models.length - 1; i >= 0; i--) {
                if ($scope.models[i].ModelId == $scope.FilteredModelIds[j]) {
                    $scope.FilteredModels.push($scope.models[i]);
                }
            }
        }
    }
}

Whenever the dropdown list changes, the filtermodelbyId() function is called and new values are pushed, but these changes only reflect after the second change on the dropdown list. Is there a better way to handle this?

Thanks!

Answer №1

It appears that $http is not being utilized in the function dataFactory.getModelIdByFilter. I suggest incorporating the following code:

$scope.$apply(function(){
  $scope.FilteredModelIds = result.data;
});

Alternatively, you can take advantage of Angular services to fetch data (assuming jQuery ajax is used).

Answer №2

Ensure that your code runs only after the $scope.FilteredModelIds variable has been assigned a value.

dataFactory.retrieveFilteredModels($scope.region, $scope.subregion).success($scope.handleSuccess).then(function (result) {
    $scope.FilteredModelIds = result.data;
    if ($scope.FilteredModelIds != null && $scope.FilteredModelIds.length > 0) {
        for (var j = $scope.FilteredModelIds.length - 1; j >= 0; j--) {
            for (var i = $scope.models.length - 1; i >= 0; i--) {
                if ($scope.models[i].ModelId == $scope.FilteredModelIds[j]) {
                    $scope.FilteredModels.push($scope.models[i]);
                }
            }
        }
    }
});

Answer №3

Here's a spontaneous guess:

function updateModelByFilter() {
    $scope.FilteredModels = [];

    dataFactory.getModelIdByFilter($scope.region, $scope.subregion).success($scope.handleSuccess).then(function (result) {
        $scope.FilteredModelIds = result.data;

        if ($scope.FilteredModelIds != null && $scope.FilteredModelIds.length > 0) {
            for (var j = $scope.FilteredModelIds.length - 1; j >= 0; j--) {
                for (var i = $scope.models.length - 1; i >= 0; i--) {
                    if ($scope.models[i].ModelId == $scope.FilteredModelIds[j]) {
                        $scope.FilteredModels.push($scope.models[i]);
                    }
                }
            }
        }
    });
}

Revise the model array in the callback.

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

Ways to troubleshoot an issue that arises when the `onChange` event is not utilized in a radio button component on a

When using this component for radio buttons without the Onchange function, I sometimes encounter the following error on the page related to onUpdate: TypeError: this.props.onUpdate is not a function onChange(e) { let value = e.target.value; this ...

How can you deactivate the Formly form in AngularJS?

Is there a way to completely disable the formly form instead of just the fields? I want to disable the entire form so that it is truly disabled, not just in readonly mode. Can anyone offer some guidance? Here is an example of my current code. I am lookin ...

Is there a way to specifically execute a Mongoose validate function solely for the create user page and not the edit user page?

Exploring Different Tools In the process of developing a website using Node.js, Express, and MongoDB. Leveraging mongoose for interacting with the MongoDB server has been quite beneficial. However, I encountered an issue where a function within my Mongo ...

Using a carousel component in Bootstrap

Just starting out with this, trying to customize Bootstrap to change slides automatically. I followed the documentation at https://getbootstrap.com/docs/4.3/components/carousel/ but for some reason, the slides aren't changing on an interval, even thou ...

Can input type text be styled using CSS3 for updates?

Displayed below is a sample keyboard layout: Each number on the screen can be clicked to update the text area. Clicking the backspace key will remove the last number entered. To clear all content in the text area, click on the clear all button. Use t ...

Updating a SharePoint list item by retrieving a field value from a people picker field

I am attempting to update an SP.Listitem by replacing an spUser with another user using JSOM. Below is the code snippet: // Query the picker for user information. $.fn.getUserInfo2 = function () { var eleId = $(this).attr('id'); var siteUrl ...

Display a specific tab section upon clicking using jQuery or JavaScript

Hello everyone! I am completely new to JavaScript. I have added a tab slider to my HTML with 3 categories in the tab menu: All, Creative, and Branding. How can I show a div after clicking on one of the list items? I have assigned classes to the list items ...

I am encountering a challenge retrieving the ID via AJAX from the view to the controller. However, the ID is successfully displaying in the alert

In the view page code below, I am trying to send an ID through Ajax but it is not posting in the controller. The goal is to replace one question at a time fetching from the database. $(document).ready(function() { $("#next").click(function() { ...

Twilio - Organizing call records by time stamps

I'm currently working with nodejs and have code that fetches all Twilio calls like below: client = require("twilio")(accountSid, authToken); client.calls.list({ }); Now I want to filter the Twilio calls based on a specific start and end date range. ...

There seems to be this strange and unexpected sharing of Animated.View and useRef between different child components

Currently, I am displaying a list of items in the following manner: {formattedJournal[meal].map((food, idx, arr) => { const isLast = idx === arr.length - 1; return ( <View key={idx}> ...

How can UI tests be run in headless mode in Selenium 4 and above?

Selenium recently announced the release of Selenium 4, and they have also mentioned that there will be no support for PhantomJS from Selenium 4 onwards. Does this mean that Selenium no longer supports headless automation, or is there a different method t ...

Retrieve Data from an Object using a Different Value

It sounds silly, but I'm struggling with this. I'm working with a basic JS object: var objSyntax = [ {"a": "1"}, {"b": "2" }, {"c": "3"} ]; My goal is to retrieve the value associated with key 'a&apos ...

Leveraging JSON for parsing xmlhttp.responseText to auto-fill input fields

Is there a way to utilize JSON for parsing xmlhttp.responseText in order to populate textboxes? I've been struggling to achieve this using .value and .innerHTML with the dot notation, along with b.first and b.second from the json_encode function in th ...

RadScheduler refresh rate

Currently I am incorporating RadScheduler into my project. The scheduler requires a regular update, so I have implemented a JavaScript function with an interval to call rebind() on the RadScheduler every 60 seconds. However, an issue arises when the user o ...

Adding a JavaScript widget to a WordPress page

Good morning! I need to place an affiliate external widget on a WordPress page. The code I have loads external content within the page. <script type="text/javascript" src="http://www.convert.co.uk/widget/mobiles.js"></script> The placement o ...

$routeProvider fails to catch all cases initially

Recently, I've started working with Angular and I'm facing a problem with my routes. I'm building an Angular SPA with .NET MVC, and although the views are rendering, I've noticed that there are two footers appearing on the page, which l ...

Determining the Next Available Date from JSON Data

I have a task of using a JSON response from the Eventbrite API to showcase the upcoming event tour date. The goal is to automatically calculate this date based on the current time, identifying the next event after the current moment. Below is the JSON res ...

Issue with binding classes dynamically in vue with svg elements

I'm attempting to create a custom typing program for one of my students using SVG to display the words and class binding with Vue.js. The goal is to change the color of the characters when the correct key is pressed by the user. However, I've enc ...

React Native error - "Invalid element type: expected a string or class/function, but received undefined" - encountering issue with importing a custom library?

Alright, I'm looking to make some modifications to this library, so I am attempting to import the non-transpiled version by downloading the repository and importing it from here: https://github.com/nicotroia/react-native-floating-action-menu#readme A ...

Interact with the Django server API from a locally running Angular application

Currently, I am in the process of learning Django and Angular frameworks for web development. After setting up a Django API back-end on http://serverip:8666/athletics/, I proceeded to create a simple Angular application which I have been testing from my o ...