Passing data from input to Angular's $scope (filter)

I'm currently working on my first custom filter, and while the basic principle is functioning (it displays all the CDs of an artist from 7 and up), I'm encountering an issue where the filter doesn't update when I change the value. It consistently remains at "7". Here's what I have so far:

HTML INPUT

<input type="number" value="7" id="numberOfCdsByArtist">

CONTROLLER:

$scope.filterCDs = function (Artist) {
    var numberOfCdsByArtist = $('#numberOfCdsByArtist')[0].value;
    return Artist.numberOfCDs >= numberOfCdsByArtist ;
}

NG-REPEAT:

<div class="Artists" ng-repeat="Artist in Artists | orderBy:'Name' | filter:filterCDs">
  <div>{{Artist.Name}}{{Artist.numberOfCDs}}
</div>

Answer №1

let countOfAlbumsByPerformer = $('#countOfAlbumsByPerformer')[0].value;

Eliminate the above jquery statement from the controller and consider utilizing an ng-model directive instead. This way, only Angular will be able to detect any changes in the model.

angular.module('A', []).controller('C', function ($scope) {
  $scope.albumCount = 0;
  $scope.performers = [
    { name: 'Performer 1', albumCount: 1 },
    { name: 'Performer 2', albumCount: 2 },
    { name: 'Performer 3', albumCount: 3 },
    { name: 'Performer 4', albumCount: 4 },
    { name: 'Performer 5', albumCount: 5 },
    { name: 'Performer 6', albumCount: 6 },
    { name: 'Performer 7', albumCount: 7 }
  ];
  
  $scope.albumNumFilter = function (performer) {
    return performer.albumCount >= $scope.albumCount;
  }
  
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular.min.js"></script>
<section ng-app="A" ng-controller="C">
  
  <input type="number" ng-model="albumCount" min="0"/>
  
  <ul>
    <li ng-repeat="performer in performers | filter: albumNumFilter">{{ performer.name }}:{{ performer.albumCount }}</li>
  </ul>
  
</section>

Answer №2

The reason you're not getting the desired result is because you're not following Angular's standards.

Try formatting it like this:

<input type="number" ng-model="numberOfCdsByArtist">

Make sure your controller's scope includes the property numberOfCdsByArtist

It should be defined as follows:

$scope.numberOfCdsByArtist = 7;

Additionally, take some time to understand how custom filter functions are implemented in AngularJS. Check out this resource for more information here.

Answer №3

Take a look at my customized filter in action on jsfiddle. It might come in handy for you...

JSFiddle custom filter demo

var app = angular.module("myApp", []);

app.controller("MyCtrl", function($scope) {
  $scope.numberOfBooksByAuthor = 5;

  $scope.Authors = [{
      "Name": "author1",
      "numberOfBooks": 10
    }, {
      "Name": "author2",
      "numberOfBooks": 3
    }, {
      "Name": "author3",
      "numberOfBooks": 7
    }];

});

app.filter("customFilter", function() {
  return function(input, bookNumber) {


    var out = [];
    angular.forEach(input, function(author) {
      if (author.numberOfBooks >= bookNumber) {
        out.push(author);
      }
    });
    return out;
  };

});
<div ng-controller="MyCtrl">
  <input type="number" ng-model="numberOfBooksByAuthor">

  <div class="Authors" ng-repeat="Author in Authors | customFilter:numberOfBooksByAuthor ">
    <div>{{Author.Name}} :- {{Author.numberOfBooks}}
    </div>

  </div>

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

Troubleshooting issues when testing Angular services using Jasmine and Chutzpah

I've been facing some challenges while attempting to test my AngularJs services with Jasmine as I encounter various errors consistently. In an effort to troubleshoot, I decided to create a simple Sum service for testing purposes but unfortunately, the ...

establishing communication between the angular controller and route controller

index.html <body> <div data-form-modal > <form> <input type='text' name='test'/> <input type='submit' value='submit' ng-click='submit()'/&g ...

Angular js is a powerful framework that allows for the seamless transition of views, except for the home

I am currently using the ng-animate module to implement sliding effects for my app views. Each route has its own unique slide animation. Take a look at my simple code below: HTML: <div ng-view ng-animate class="slide"></div> CSS: /*Animatio ...

Strategies for resolving duplicate jQuery code in my project

Trying to simplify my jQuery code that handles video selection and playback functionality. Users can click on a thumbnail or button to play a specific video, with the title of the video changing accordingly. Despite achieving the desired outcome, the cur ...

Jenkins process encounters issues with sed execution

I am currently facing an issue where a script that runs successfully locally encounters difficulties during our Jenkins build process, specifically with the 'sed' command. Below is the code snippet I am using. I have double-checked the file path ...

How to send arguments to a callback function in Next.JS

Here's the code snippet I'm working with: import Router from "next/router"; import React from "react"; export default function MainIndex() { return (<React.Fragment> <h1>Main Index Page</h1> ...

Store Dark Mode preferences in the browser's local storage using React and Material-UI

Is there a way to save the dark mode setting in localStorage? Can this approach be used for storing it? Any suggestions on how to achieve this would be appreciated. Thanks, cheers! function App() { const [darkState, setDarkState] = useState("&qu ...

Why isn't the page being redirected when attempting to use JavaScript with window.location and window.location.href?

Currently, I have implemented a login system on my website. The process involves triggering an ajax request to a designated PHP script upon the user clicking the submit button. This script is responsible for logging in the user and responding with the mess ...

The result of Coordinates.speed is consistently null

I'm working on a project that involves changing the speed of background particles based on the user's device speed (like when they are in a car or bus). I thought the Geolocation API would be a perfect fit, specifically the Coordinates.speed prop ...

The issue with Ionic 2 arises when attempting to use this.nav.push() because it

Recently transitioning from Ionic 1 to Ionic 2, I'm encountering an issue with using this.nav.push(nameOftheOtherPage) immediately after a promise. Interestingly, the function this.nav.push works fine when it's called outside of the promise funct ...

Side-by-side arrangement of AngularJS Accordion in a vertical layout

I am looking to change the layout of the accordions from being stacked on top of each other to being displayed side by side. I have attempted to add a span above the accordion-group but it did not provide the desired effect. <div id="top-panel" style=" ...

The Transition Division Is Malfunctioning

I've encountered an issue where I am trying to move a div by adjusting its left property, but no transition is taking place. Regardless of the changes I make to my code, the result remains the same. Below is the current state of the code. Can anyone i ...

Tips for comparing two arrays in node.js

I am faced with the task of comparing two arrays. let runArray = ['Welcome', 'Hello'] let data = [{ Node:'Good', Session:'2', Run:'Welcome', Run_Group:'Display', Elapsed_Ms: '1000& ...

The best practices for utilizing getStaticProps with Firebase

I am completely new to Next.js and am struggling to make the getStaticProps function work properly. import firebase from '../firebase' export default function Home({ posts }) { return ( <div> <h1>All Posts</h1> ...

Guidelines on launching an ionic 4 modal using routes

How can I open a modal using routes? I attempted the following approach, but it did not work as expected: ngOnInit() { this.launchModal(); } async launchModal() { const modal = await this.modalController.create({ component: AuthPasswordR ...

Dealing with special characters in Mustache.js: handling the forward slash

I have a JSON file that contains information about a product. Here is an example of the data: { "products": [ { "title": "United Colors of Benetton Men's Shirt", "description": "Cool, breezy and charming – this s ...

Refresh the content of VueJS Resource

Resource file helper/json_new.json { "content": { "content_body": "<a href='#' v-on:click.prevent='getLink'>{{ button }}</a>", "content_nav": "", } } Vue script.js file new Vue({ el: 'body', ...

Tips for invoking a url with JavaScript and retrieving the response back to JavaScript

I am trying to make a URL call from JavaScript with a single parameter, and the URL should respond to that specific request. Here is an example of the response format: {"success":true, "result": {"token":"4fc5ef2bd77a3","serverTime":1338371883,"expireT ...

Encountering an unrecoverable SyntaxError while trying to deploy a website on Netlify

When using commands like npm start, npm run build, and pm2 start server.js, everything runs smoothly without any errors. However, I encounter an issue when trying to deploy my project on Netlify. The Chrome console displays the error: Uncaught SyntaxError: ...

Using Typescript: How to pass a function as an argument in another function

In my angular application, I am working on the following setup: this.myServiceOne.getDataOne().subscribe((res => {this.variableOne= res})); this.myServiceTwo.getDataTwo().subscribe((res => {this.variableTwo= res})); this.myServiceThree.getDataThree( ...