AngularJS - Move the <li> element to the top when its corresponding checkbox is selected

This particular question pertains to a topic that was previously discussed in another thread

The scenario involves using a ng-repeat as shown below:

<li ng-repeat="opt in namesCtrl.uniqueCars">
    <input type="checkbox" ng-model="namesCtrl.filter['cars'][opt.element]" | orderBy:['checkbox','-count']"><p2>{{opt.element}} ({{opt.count}})</p2>
</li>

In this setup, the elements are derived from this.uniqueCars

this.uniqueCars=[
    {'element':'Ford','count':3,'checkbox':false},
    {'element':'Honda','count':2,'checkbox':false},
    {'element':'Ferrari','count':1,'checkbox':false},
    {'element':'Delorean','count':6,'checkbox':false}
];

Checked items on the display list are then sent to this.filter for a separate purpose

this.filter = {
    "cars": {}
}

The main objective here is to sort the checkbox list visible in the view so that when an item is checked, it moves to the top of the list. The intended result should resemble something like this

To achieve this, there is a $watch implemented in the following manner:

$scope.$watch("namesCtrl.filter", function(nv,ov){
    angular.forEach(self.uniqueCars, function(opt){
    opt.checkbox = nv.cars[opt.element]
    })
}, true)

However, the behavior observed during sorting based on the checkbox value is inconsistent. When initially clicked, it works fine, but upon unclicking, the sorting does not work properly. Clicking again results in reverse ordering.

Hence, the aim is to refine this functionality by modifying the existing $watch. This approach is chosen because real-life scenarios may involve modifications to this.filter by other elements, necessitating constant monitoring of changes.

Note: the addition of the this.uniqueCars.checkbox field is done intentionally to enable proper sorting and can be adjusted accordingly.

You can access a functional example on Plunker here.

Answer №1

Great effort, but there was a minor issue with your implementation involving the $watch function. In cases where a car is not yet a member of namesCtrl.filter, its checkbox value gets removed from namesCtrl.uniqueCars because it's undefined.

$scope.$watch("namesCtrl.filter", function(nv,ov){
  angular.forEach(self.uniqueCars, function(opt){
    var value = nv.cars[opt.element] ? nv.cars[opt.element].checkbox : false;
    opt.checkbox = value;
  });
}, true);

To resolve this and ensure proper ordering, you can order by checkbox in reverse as well:

<li ng-repeat="opt in namesCtrl.uniqueCars | orderBy:['-checkbox','-count']">

For a working example, refer to this plunker.

Answer №2

Is it not possible to directly modify the checkbox property itself? By changing the input's model to opt.checkbox and removing the watch, everything seems to function properly. In my opinion, this approach works better.

Alternatively, you could update

opt.checkbox = nv.cars[opt.element]
to
opt.checkbox = !!nv.cars[opt.element]
to achieve the same result (the checkbox property in the cars object is initially undefined, causing issues with correct ordering).

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

The onbeforeunload event is activated in the parent page when it is specified in the child page

Seeking a way to activate the window.onbeforeunload method when a user attempts to refresh the browser, and display a message to prompt them to save their current work before leaving. I am currently working on an AngularJS application. Here is the URL of m ...

Leveraging JavaScript within the Selenium JavaScript Executor

I am trying to check if the required text is visible on the page, but I am unable to use the gettext() method from Selenium WebDriver due to a permission exception. As a workaround, I have created a JavaScript script to compare the text. String scriptToE ...

Having trouble with the DataTables jQuery plugin? Seeing a blank page instead of the expected results?

I've been trying to set up the Datatables jquery plugin for my HTML table but it's not working as expected. I have linked to the Datatables CDN for CSS styling and script, along with Google's hosted jQuery plugin. Additionally, I have a loca ...

Using Angular 5 to access a variable within a component while iterating through a loop

I am currently in the process of transferring code from an AngularJS component to an Angular 5 component. Within my code, I have stored an array of objects in a variable called productlist. In my previous controller, I initialized another empty array nam ...

What is the best way to extract the class name from ui.item or event using the function(event, ui)?

Is there a way in jQuery to extract the class name from a function with two parameters, event and ui? For example, consider the following code snippet: $(document).tooltip({ show: null, position: { my: "left top", at: "left bottom ...

Utilize Meteor and Mongo to access a nested array object in a template with spacebars

I am trying to populate the content of a textarea by extracting data from a nested array. In my helper function, I have specified the document id and the element id. The goal is to extract the content of the text field from the findOne result and display i ...

Tips for showing more rows by clicking an icon within an Angular 2 table

When I click on the plus (+) button in the first column of each row, only one row expands. How can I modify it to expand multiple rows at a time? Thanks in advance. <div> <table class="table table-striped table-bordered"> <thead> ...

An issue arises when attempting to iterate over an object literal using ng-repeat in AngularJS

I am currently learning angular js and practicing filters. I have successfully been able to iterate over an array of objects, but when trying to work with objects within objects, my browser is throwing an error: "Uncaught SyntaxError: Unexpected token" &l ...

Setting up the initial 3 parameters in a v-for loop

What is the best way to begin a v-for loop? For instance, we have an array named "array" with the following values: array = [dog, cat, e, f, g]; I am interested in using a v-for loop that will start looping through and only consider the first 3 values. ...

Spinning objects in three.js using tween.js to move around the global axis

Currently, I am working on tween-rotating a 3D cube. Thanks to this helpful post (How to rotate a object on axis world three.js?), I have successfully achieved rotation without any issues. Now, my goal is to transfer the rotation achieved through setFromRo ...

What are the steps to accessing validation errors using express-validator?

Recently, I delved into the world of express-validator to enhance my skills. Despite going through the documentation thoroughly, there's a query lingering in my mind that might have already been addressed in the docs. My confusion arises from needing ...

Inject the code snippet from CodePen into a WordPress webpage

I have a WordPress page where I want to integrate the HTML, CSS and JS code from my Codepen project. The styling appears to be working correctly, but the JavaScript is not functioning as expected. You can view the page here: Could someone assist me in pr ...

Material-UI: Issues with functionality arising post library update

I recently switched from material-ui version 0.14.4 to 0.15.4 and encountered some issues while trying to make my code work. Below is an excerpt from my code: var React = require('react'), mui = require('material-ui'), LoginDialog ...

Chrome geolocation feature does not display the permission popup for JavaScript

After the latest Chrome update, we have noticed that the popup to Allow/Block accessing a user's location from a website is no longer appearing. We tested this on Edge, Firefox, and different mobile devices, where it seems to be working fine. Current ...

Issue: Incorrect parameters for executing the MySQL statement

Currently, I am working on a nodeJs project and utilizing the npm package mysql2 for connecting to a MySQL database. This is how my MySql Configuration looks like:- let mysql = MYSQL.createConnection({ host: `${config.mysql.host}`, user: `${config.mys ...

When an option is selected in one dropdown, a list is dynamically populated in another dropdown. However, the entire column then displays the selected row's options in a table format

https://i.stack.imgur.com/q7tMT.png Upon selecting an option from a dropdown within a table row, I make a call to an API to fetch a list of strings into another dropdown field for that specific row. However, the entire column is being populated with that r ...

The error message "res.jwt is not a function" is commonly encountered when using Node

I kept receiving the error message: res.jwt is not a function I have installed jwt-express and imported it like this: import jwt from 'jwt-express' This is my auth.js file: import Account from '../services/account.js' import env from ...

Android Webview onLoad function provides incorrect height information

When I load a file:// URL into the webview, issues with height calculation arise. Instead of using WRAP_CONTENT, I calculate the height in javascript during the onPageFinished event in Android. However, about 2 out of 5 times, the javascript reports an inc ...

Choosing an option from a dropdown menu by extracting information from JSON content

My goal is to develop a basic jQuery plugin that interacts with a geolocation system to provide data on the location of the user's IP address and then automatically select the corresponding country in an HTML form. Within my HTML code, I have a selec ...

How can a button be linked directly to a particular list item?

I currently have a HTML tag within my React application that looks something like this: <ul> <li> Item 1 <button> Delete </button> </li> <li> Item 2 <button> ...