Refreshing the state when making changes to ng-repeat through orderBy and/or filter

I'm new to Angular JS and while I understand JavaScript in general, Angular has a different approach that is challenging for me. Specifically, I am struggling with sorting an array of objects by a property and filtering them based on a string provided by the model attached to an input field "query."

Everything seems to be working well until I encounter the issue of preserving the objects grouped by the "group" property when the array is filtered by a keyword entered in the input field.

<input ng-model='query' type='text'>    
<div ng-repeat='reservation in reservations | filter: query | orderBy: "group"'>
  <span as-reset-list='{{$last}}'></span>
  <h2 ng-show='CreateHeader(reservation.group)'>Group</h2>
  <div>Group:  {{ reservation.group }} - ID: {{ reservation.id }}</div>
</div>

To display a header indicating the group, I have created a variable "currentGroup" in the $scope so that I can compare it with the current object's group within the loop.

function RestaurantCtrl($scope) {
  $scope.restaurants = [/* data */];
  $scope.currentGroup = '';

  $scope.CreateHeader = function(group){
    showHeader = (group!=$scope.currentGroup);
    $scope.currentGroup = group;
    return showHeader;
  }
}

However, when I perform a search that returns no results and then do another search, it seems like the variable loses its value or something happens that causes the grouping not to work as expected.

How can I solve this issue? I've attempted creating a directive to reset the value of the "currentGroup" variable but it doesn't always work.

You can view a working example of my code here http://jsfiddle.net/5HZYt/

Answer №1

Your issue may stem from how you are setting ng-model. It seems like you are assigning ng-model to a basic scope variable, resulting in the binding being lost when the variable changes. To prevent this problem, consider setting ng-model to a property of an object so that Angular maintains a reference to the object.

For example:

$scope.dataObject = {property: "This Example"};

Then, use:

<input ng-model='dataObject.property' type='text'>

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

Is the OR (||) operator malfunctioning in the Angular.forEach method?

I am faced with the challenge of manipulating a JSON array by applying certain conditions for removal: var data = [ {data1: "aaa", data2: "bbb", data3: "ccc"}, // First {data1: "ddd", data2: "eee", data3: "fff"}, // Second ...

Utilize a personalized useFetch hook in React.js to transmit a POST request and obtain a response

I recently came across a great resource on this website that provided the logic for a useFetch hook. My goal is simple - I want to send a post request and then map the response into a specific type. While this seems like it should be straightforward, I&apo ...

What issues are present with the JavaScript event management in this scenario? (Specifically using the click() and hover() jQuery functions)

Currently, I am in the process of developing a proof-of-concept for a project that mimics Firebug's inspector tool. For more detailed information, please refer to this linked question. You can view an example page of my work which has only been teste ...

What is the most effective method for establishing functions in AngularJS?

Hey there, I'm currently working on a function in AngularJS and I'm not sure what the best practice is for defining methods. Any suggestions would be greatly appreciated. Option 1: var getBranchKey = function(currentBranchName) { }; Option 2: ...

Manipulate properties of objects with React by assigning values from an array

I am working with various objects and values in my code: const [validFilters, setValidFilters] = useState({}); const [endedEvents, setEndedEventsSort] = useState(false); const [joinedEvents, setJoinedEventsSort] = useState(true); const [startDate, setStart ...

The sequencing of code execution in JavaScript (illustrated using an example in d3-force)

I'm currently delving into this code to grasp the inner workings of d3-force. As I examine the variable nodes, I am intrigued by how positions are assigned to them. // Replace the input nodes and links with mutable objects for the simulation. con ...

Is it possible for Node.js to not automatically restart the server when modifying .js files?

Right now I have node-supervisor set up to detect changes in .js files, and while it works well, I've realized that it restarts the server every time a js file is saved. Is there a way to save a server-side .js file without triggering a server restart ...

What is the best way to conceal my class element if the data-reviews number is under 5?

I have been experimenting with basic JavaScript for the data-reviews="2" scenario and it worked successfully. However, what I am aiming for is to hide the entire <span> section when the value of data-reviews is less than 5 or any specific ...

Error Message: Error Code 2. I am encountering an issue with the bot expecting either undefined or null and receiving a string primitive instead. Any

As I delved into creating a music bot with support for slash commands, everything seemed to be going smoothly when embedding a URL to a single song. However, the trouble began when attempting to include a link to a playlist, resulting in two perplexing err ...

Unchecking radio buttons in Knockout without losing synchronization with the View Model

I am facing an issue with implementing selected/unselected radio buttons. The radio buttons are being generated dynamically from a database source. <tbody data-bind="foreach: attByGroups" <-- ko foreach: attributes --> <input type="ra ...

Using Radio button to access local HTML pages - A step-by-step guide

I am currently working on a project that involves the use of radio buttons and their corresponding options. My goal is to have each radio button selection lead to a specific HTML page being displayed. I've come across solutions involving external URLs ...

Can you explain the mechanism behind how the spread syntax (...) interacts with mapGetters?

When implementing a computed getter using the mapGetter helper from Vuex, the syntax typically involves using the spread operator in the following way: ...mapGetters([ 'getter1', 'getter2', 'etc' ]) Although th ...

Animating nested ng-repeat loops

Trying to animate a list of elements divided by rows (the parent ng-repeat) and columns (the child ng-repeat) has been quite challenging. While I was able to achieve the desired animation with individual ng-repeats, the same cannot be said for nested ng- ...

Constructing Django forms for displaying form fields from multiple models arranged based on a foreign key

I've hit a roadblock with this issue - despite trying various approaches, I keep encountering a "too many values to unpack" error upon form submission. Here's a brief overview of the models involved in this scenario: class Supplier(models.Model ...

An error has been encountered in Angular where a source map issue is causing a TypeError due to the

Whenever I work on an Angular project, the browser console usually remains error-free. However, when I opt to include projects > project-name > architect > build > options > "optimization": false in the angular.json file to deactiv ...

Tips on increasing video size upon visiting a website. HTML, JavaScript, and potentially jQuery can be used for video animation

Is there a way to create a video pop-up in the same window when visiting a website? I want the video to increase in height from 0 to a specific height and move slightly upwards. Are there JavaScript or jQuery functions that can achieve this effect? I wou ...

Pressing an HTML button can enable and disable the pause and resume functions

Currently, I am working on an audio player where I need to implement functionality to pause and resume the playback. I have already set up the pause() and resume() functions in my script. The issue I am facing is related to the HTML button that triggers th ...

Enhance your Rails 5 application with a dynamic live search feature powered by Keyup. Say goodbye to

Currently, I have a Rails 5.1.3 application with a simple contact model that stores names and phone numbers. To enable searching within the index view/page, I am utilizing Ransack. A keyup event listener written in Coffeescript captures user input as they ...

Exploring the differences between two CSS style attributes using JQuery

Can someone help me with a quick question about CSS? I need to compare two style attributes, specifically margin-left. If the margin-left is less than 500px, I don't want to make any changes. However, if it's greater than 500px, I want to add ano ...

Issues with the controller not functioning properly in AngularJS version 1.3

Utilizing one controller in two different sections of a page, I am using an alias for the controller using the "controller as" syntax. However, after updating to Angular 1.3.15, this method no longer works. Below are links to fiddles demonstrating the issu ...