Using AngularJS to dynamically modify filter choices

Seeking something similar to this example in the documentation, but with a unique input that can serve as a filter for "any", "name", or "phone" properties. The role switching is triggered by clicking an anchor tag. Check out the code snippet here: http://jsfiddle.net/ubugnu/QuyCU/. How can I update the ng-model attribute dynamically?

HTML

<div ng-app>
  <div ng-controller="MainCtrl">

      <label>Any</label> <input type="text" ng-model="search.$"> <br>
      <label>Name only</label> <input type="text" ng-model="search.name"><br>
      <label>Phone only</label> <input type="text" ng-model="search.phone"><br>

      <div style="background-color:#FAE8F1">
      <hr>

      <label>Filter</label> <input type="text" ng-model="search.$"> by {{filter}} <br>
      <ul>
      <li><a href="" ng-click="changeFilterTo('$')">Any</a></li>
      <li><a href="" ng-click="changeFilterTo('name')">By Name</a></li>
      <li><a href="" ng-click="changeFilterTo('phone')">By phone</a></li>
      </ul>

      <hr>
      </div>

      <table class="table">
        <tr><th>Name</th><th>Phone</th></tr>
        <tr ng-repeat="friend in friends | filter:search">
          <td>{{friend.name}}</td>
          <td>{{friend.phone}}</td>
        </tr>
      </table>
  </div>
</div>

JS

function MainCtrl($scope, $http) {
    $scope.friends = [{name:'John', phone:'555-1276'},
                      {name:'Mary', phone:'800-BIG-MARY'},
                      {name:'Mike', phone:'555-4321'},
                      {name:'Adam', phone:'555-5678'},
                      {name:'Julie', phone:'555-8765'}];
    $scope.filter = "$";
    $scope.changeFilterTo = function(pr) {
        $scope.filter = pr; 
    }
};

Answer №1

To dynamically change the variable to which ng-model is bound, you can define it like this: ng-model="search[filter]" (where filter is another $scope variable).

Check out the fiddle for an example: http://jsfiddle.net/lopisan/vzQKk/1/

Make sure to include this line in the controller:

$scope.search = {name:'', phone:'', $:''};

Then update your input like so:

<input type="text" ng-model="search[filter]">

Answer №2

Consider this method - there may be alternative ways to achieve the same result.

<div ng-app>
  <div ng-controller="MainCtrl">
      <div style="background-color:#FAE8F1">
      <hr>

      <label>Filter</label> <input type="text" ng-model="multi"> by {{filter}}         <br>
      <ul>
      <li><a href="" ng-click="changeFilterTo('$')">Any</a></li>
      <li><a href="" ng-click="changeFilterTo('name')">By Name</a></li>
      <li><a href="" ng-click="changeFilterTo('phone')">By phone</a></li>
      </ul>

      <hr>
      </div>

      <table class="table">
        <tr><th>Name</th><th>Phone</th></tr>
        <tr ng-repeat="friend in friends | filter:getFilter()">
          <td>{{friend.name}}</td>
          <td>{{friend.phone}}</td>
        </tr>
      </table>
  </div>
</div>

Javascript:

function MainCtrl($scope, $http) {
    $scope.friends = [{name:'John', phone:'555-1276'},
                      {name:'Mary', phone:'800-BIG-MARY'},
                      {name:'Mike', phone:'555-4321'},
                      {name:'Adam', phone:'555-5678'},
                      {name:'Julie', phone:'555-8765'}];
    $scope.filter = "$";
    $scope.multi = "";
    $scope.changeFilterTo = function(pr) {
        $scope.filter = pr; 
    }
    $scope.getFilter = function() {
        switch ($scope.filter) {
            case 'name':
                return {name: $scope.multi};
            case 'phone':
                return {phone: $scope.multi};
            default:
                return {$: $scope.multi}
        }
    }
};

Answer №3

Here is a straightforward method that utilizes radio buttons

<input type="text" ng-model="search[filter]">

<label>Filter by the following:</label>

<label>Any <input type="radio" ng-model="filter" ng-init="filter = '$'" value="$"></label>
<label>Name <input type="radio" ng-model="filter" value="name"></label>
<label>Phone <input type="radio" ng-model="filter" value="phone"></label>

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

Encountering issues when making API calls from a .NET program

I'm encountering an error when trying to call an API from a .NET application: "Script7002:XMLhttpREQUEST:Network Error 0x80070005, Access Denied." Interestingly, I am able to get the correct response when testing the API with the "Advanced Rest Cl ...

JavaScript utilized to create a fully immersive full-screen webpage

I have been trying to implement a code for creating a full-screen website that works on all browsers. Unfortunately, my current code only seems to be functioning properly on Mozilla browser. When I try to view the site in Chrome and make it full screen, it ...

What is the correct way to properly import a non-relative path in TypeScript?

Struggling with importing into my TypeScript class. // Issue arises here... import * as Foundation from 'foundation/foundation'; // Everything runs smoothly until the above import is added... export class HelloWorldScene { constructor() { ...

Enhanced efficiency in the interaction between front-end JavaScript and back-end JavaScript

As a frontend developer, I find myself in the unique position of working on a project that involves processing a large amount of data in my nodeJS backend (while using reactJS for the front end). After the necessary data processing is completed in the bac ...

Javascript-generated HTML elements are invisible

I am attempting to create a "circle of fifths" using html, css, and javascript. I am following this tutorial: https://blog.logrocket.com/interactive-svg-circle-of-fifths/ Although I am using the astro framework, I don't believe my issue is related to ...

Implementing bbcode feature in TinyMCE

Take a look at the custom html code provided below: <button type="button" class="btn btn-default btn-sm" onclick="appendBBCode('youtube','ContentArea')">[youtube]</button> <br> <div class="form-group field-boats-co ...

Setting a placeholder for an img tag in Angular: A step-by-step guide

What is the process for adding a placeholder to an image in AngularJS using the img element? I am currently setting the image dynamically with ng-src in my application. ...

The performance of Node.js Knex SQL insert queries leaves much to be desired

I have created a simple login system that performs the following actions: Verifies if the username exists (works fine) Adds the username to the database After adding the username, I retrieve the id of the added username. Everything works smoothly on the ...

Creating a personalized v-for loop with v-if to apply a specific class to a div element

How can I correctly utilize v-if when using v-for inside? I am aiming to implement a condition where if the index is 0 or it's the first data, then add an active class. <div class="item active" v-for="(item, key, index) in slideItem" :key="item._ ...

Using AJAX to submit a PHP form without refreshing the page

Currently, I am facing an issue with my PHP and AJAX code for posting data without redirecting the page. Surprisingly, the script works perfectly on the login page but not on other pages. The main difference I observed is that the login page uses if (empty ...

Leveraging Expressjs to act as a proxy for handling cross-origin requests made via AJAX

I'm working on a website that relies entirely on external APIs, without any server-side logic. All data will be retrieved from an external API. The backend server is mainly used for asset management and routing. We've decided to use nodejs with e ...

What is the best way for me to incorporate images retrieved from an API call into my

Hey everyone, this is my first time posting on here so if there's anything I'm missing, please let me know! I've run into an issue with the images on my categories page not aligning properly and being different sizes after I incorporated som ...

Updating image URL for grouped objects with Fabric JS

Check out this link :http://jsfiddle.net/mishragaurav31/ang58fcL/#base I created two groups of objects; one consisting of a circle and text, and the other with two images. When I try to change attributes for group 1, it works fine. However, when attempt ...

How to dynamically insert a new row below a specific row with a sliding animation in jQuery

My task is to create a tree-like table structure where clicking on a specific row will reveal and add new rows below it. Specifically, I am designing the Category and SubCategory structure. Currently, I can append rows after a specified row but am struggl ...

Using next.js and redux for user authentication: a step-by-step guide

After creating my next.js app with version 9.3.5, the authentication was working perfectly. However, after updating next-redux-wrapper and next.js, I noticed that when I refresh the page, the user is no longer authenticated even though the cookie still exi ...

Relocate the number of records displayed per page next to the pagination controls in datatables

Currently, I am utilizing datatables to create tables effectively using their provided example. However, I am encountering difficulty in moving the "records per page" element, which is contained within a "span6" class of bootstrap. I understand that this ...

Creating a shared observable array in KnockoutJs to be used for multiple select elements

When an employer needs to assign a specific employee and premium amount, they can click on the "Add Employee" button to reveal another form with a dropdown menu of employees and an input field for the premium amount. <select> <option>John& ...

Having trouble navigating the maze of Express routing

app.js file // home route app.get("/home", async(req, res)=>{ let allCards = await Card.find({}); let skills = await Skill.find({}); res.render("index", {allCards, skills}); }) // add new skill route app.get("/home/newskill", (req, res)=& ...

Trying out REST endpoints using curl's -X PUT command results in a 404 error code

Currently, I am delving into the realm of the MEAN stack and following along with the MEAN tutorial provided by thinkster.io. You can find the tutorial here: As of now, I am navigating through the "Opening REST Routes" section. In an attempt to PUT an upv ...

Passing a variable to a modal in AngularJS

In my project, I am utilizing https://github.com/simpulton/angularjs-wizard and have made some modifications to it (specifically changed var app to $scope). It is functioning well, however, I am facing an issue where I need to pass a variable to the open f ...