Refreshing the ng-repeat directive in AngularJS

Is it possible to refresh the ng-repeat in my Angular template after receiving filter parameters from an ajax call to the server?

Check out this JS Fiddle

Template

<div>
<div data-ng-controller="myCtrl">
    <ul>
        <li data-ng-repeat="item in values | filter:filterIds()"> 
            <code>#{{item.id}}</code> Item
        </li>
    </ul>
   </div>
 </div> 
<button ng-click="loadNewFilter()"> Filter Now</button>

Angular

var app = angular.module('m', []);

app.controller('myCtrl', function ($scope) {
  $scope.values = [
   {id: 1},
   {id: 2},
   {id: 3},
   {id: 4},
   {id: 5},
   {id: 6}
  ];

  $scope.filter = [1,2,3,4,5,6];

  $scope.filterIds = function (ids) {
        return function (item) {
            var filter = $scope.filter;
            return filter.indexOf(item.id) !== -1;          
        }
  }

  $scope.loadNewFilter = function (){
    $scope.filter = [1,2,3];      
   }
});

Answer №1

It is important to inform Angular that there have been changes in the values:

$scope.loadNewFilter = function (){
    $scope.filter = [1,2,3];      
    $scope.$apply();
}

Answer №2

You've positioned the

<button ng-click="loadNewFilter()"> filter now</button>
outside of the controller's scope.

Answer №3

I faced a situation where I had to eliminate the trackBy from my ng-repeat in order for it to properly refresh.

Answer №4

Once you receive the filter called $scope.$apply(), it triggers a refresh within your scope.

$scope.$apply(function() {
     // insert your code here
});

Answer №5

I didn't have to rely on $scope.apply() in order to witness the update. My issue was resolved when I ensured the following:

  1. The update function was being invoked from within the controller.
  2. The controller executing the update function was the same one housing the ng-repeat directive.

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

Setting a minimum width for an inline element that is not displayed as inline-block

Is there a way to set the min-width on a contenteditable div while keeping other elements inline with it? I have looked at solutions that use inline-block, but I am unable to use this behavior. When inline-block wraps, it still acts like a block element, ...

Locating the ID of the child div that was clicked within a parent div element

My HTML code snippet looks like: <div id="edit" ng-click="editFunction($event)"> <span id="1"> click1 </span> <span id="2"> click2 </span> <span id="3"> click3 </span> <span id="4"> ...

Solving the problem of endless looping in JavaScript tree structures

i have been trying to create a tree structure in JavaScript. However, when I use the add_child function to add a child to an item in the elements array, it adds the child to all items in the elements array and their children, creating an infinite loop. I ...

Warning: MongoDB Deprecation Notification

Being new to the MERN technology, I've been bothered by this warning for quite some time now: "DeprecationWarning: Mongoose: findOneAndUpdate() and findOneAndDelete() without the useFindAndModify option set to false are deprecated." But I'm not u ...

State in Vuex is not kept intact after redirection to another page

Inside my Vue.js application, I have created a method for logging in users. This method sends a POST request to the server with the username and password, stores the returned data in Vuex store, and then redirects the user to the home page: login: func ...

Avoiding PHP Execution When Loading From Browser Cache?

One thing I'm trying to understand is how sites like Facebook keep their dynamically generated sidebars, such as the "People you may know," consistent even when users navigate back and forth through their browsing history. On my own site, however, eve ...

When setting AngularJS $locationProvider.html5Mode(true), an error occurs stating `url is undefined`

I've been experimenting with html5Mode for AngularJS URLs and encountered an issue. The following code functions as expected: .config(["$routeProvider", "$locationProvider", function($routeProvider, $locationProvider){ $routeProvider.whe ...

How can I use jQuery to create a new div element if it is not already present

I am familiar with how to add a class if it does not already exist, for example: $("ul:not([class~='bbox'])").addClass("bbox"); Alternatively, if(!$("ul").hasClass("class-name")){ $("ul").addClass("bbox"); } However, I am unsure how to c ...

Using Bootstrap 4 beta for Form Validation

I'm struggling to grasp the concept of building validation forms. The bootstrap documentation includes a JS code snippet (referred to as starter code) like the one below: <script> // Example starter JavaScript for disabling form submissions if ...

Adjusting the options in the subsequent dropdown menu based on the selection made in the initial dropdown menu

I am currently working on select boxes where values are dynamically added through an array. For example, if I have 4 values in the first select box, I only want to display 3 values in the second select box, excluding the value that has already been selecte ...

What could be causing my overloaded controller methods to not be receiving requests correctly?

Within my view, I have a page called PrintPatientConsent.aspx that I need to call for two different types. However, only the default action method is being called by default, even when passing parameters. Here is the code snippet for reference: [Accept ...

The use of asterisk (*) in importing dynamically

Hello everyone, I'm currently working on a project structure that looks like this: intranet ├── modules │ ├── storage │ │ ├── views │ │ └── route │ │ └── index.js │ │ │ ├── ...

Tips for providing a directory as the source in Mirth Connect version 2.2.1

I am currently using Mirth Connect version 2.2.1. I am in the process of creating a channel where the source input is a directory with multiple subfolders, each containing files. The issue I am facing is that the source can only read files placed in the pa ...

Make sure to load the gif image before any other images are loaded from the css

Hey there, I'm attempting to display a GIF image before the actual image loads. I found a great example to accomplish this: Example: Java Script function loadimage(imgsrc, change){ var loadimage = new Image(); loadimage.onload = changesrc(imgsrc, c ...

Arrays store values by reference, so when comparing their pointers, they should point to the same values in order to evaluate as true

In my understanding, arrays and objects act as pointers, pointing to a specific memory location. In the given example, when var a is updated, b should also be updated since it points to the same memory location as a. The expected final result would be tru ...

Finding queries in MongoDB collections seem to be stalling

I have been attempting to create a search query to locate a user by their username. Here is the code: userRouter.get('/user/:user_username', function(req, res) { console.log("GET request to '/user/" + req.params.user_username + "'"); ...

Changing the default yarn registry for a specific project

Typically, I fetch packages from the internal server by using the command: yarn config set registry http://custom-packages-server.com However, for a new project, I want to switch back to the default registry without affecting other projects. If I try cha ...

Encountered a problem when trying to add an onclick event to dynamically created HTML: Uncaught SyntaxError: Unexpected identifier was

Utilizing ajax to fetch results from the code behind, I am dynamically creating divs upon receiving those results. The process works smoothly without any issues. Now, my objective is to attach an onclick event to each div that triggers a specific method w ...

Click text when using the Google Tag Manager - gtm.click {{Click Text}}

I have a list of shops with detailed information like opening hours and phone numbers. When a user clicks on the shop's name, I want the relevant details to appear using javascript. I am trying to capture the shop's name (SHOP NAME) when a user ...

Convert a string that represents a Buffer into an actual Buffer object

I am looking for a way to change a string representing a Buffer into the actual encoded string. For instance, if I start with the string var str1 = "hello,there" And then convert it into a buffer using Buffer.from() buf1 = Buffer.from(str1) <Buffer ...