Toggle search mode on the fly

Just dipping my toes into the world of angularjs, so please bear with me! I'm experimenting with angularjs and trying to figure out how to dynamically set the search mode. I've attempted to do so with the code below, but haven't had much success.

<html>
    <head>
        <meta charset="utf-8">
        <title>Binding</title>
    </head>
    <body>
        <div data-ng-app="myApp">
            <input type="text" data-ng-model="{{mysearch}}" />
            <select data-ng-model="mysearch">
                <option value="search.$">All</option>
                <option value="search.name">Name</option>
                <option value="search.email">Email</option>
            </select>
            <span>{{mysearch}}</span>
            <div data-ng-controller="MyCtrl">  
                <table>
                    <tr data-ng-repeat="actor in rows.cast | filter:search">
                        <td>{{actor.name}}</td>
                        <td>{{actor.email}}</td>
                    </tr>
                </table>
            </div>
        </div>

    <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
    <script>
       var myAppModule = angular.module('myApp',[]);
       myAppModule.factory('Avengers',function(){
           var Avengers = {};
           Avengers.cast = [{name:'joe',email:'<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3f55505a7f52464c564b5a115c5052">[email protected]</a>'},{name:'david',email:'<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ef8b8e99868baf82969c869b8ac18c8082">[email protected]</a>'},{name:'charles',email:'<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="680b00091a040d1b5b2805111b011c0d460b0705">[email protected]</a>'}]
           return Avengers;
       });
       function MyCtrl($scope,Avengers){
          $scope.rows = Avengers;
       } 

    </script>
    </body>
</html>

Answer №1

The information provided states the following:

http://docs.angularjs.org/api/ng.filter:filter

When using this filter, there are different parameters to consider such as an array – {Array} – representing the source array and expression – {string|Object|function()} – being the predicate used for selecting items from the array. This can be a string which results in a substring match with the value of the expression string. If the predicate is negated, it must be prefixed with !.

An object can also be used as a pattern object to filter specific properties within objects in the array. For instance, using {name:"M", phone:"1"} as a predicate will result in an array of items where the property name contains "M" and the property phone contains "1". The $ property can be utilized (like {$:"text"}) to match any property of the object, similar to a simple substring search using a string.

A function can serve as a predicate function to write custom filters, where the function is executed for each element in the array. The final outcome is an array of elements that returned true based on the predicate.

Suggesting the inclusion of two input fields - one for name and one for email, then passing an object to the filter corresponding to the data model's name and email fields.

Additionally, creating custom filters is a feasible option as they are relatively straightforward to implement.

Answer №2

I figured it out by myself :)

<!DOCTYPE html>
<html>
<head>
<title>AngularJS Tutorials</title>
<link rel="stylesheet" href="//cdn.jsdelivr.net/foundation/4.3.1/css/foundation.min.css">
</head>
<body>
    <div ng-app="myApp">
        <div ng-controller="AvengersCtrl">
            <select ng-model="mysearch" ng-change="change()">
            <option value="$">All</option>
            <option value="name">Name</option>
            <option value="character">Character</option>
        </select>
            <input type="text" ng-model="search[filter]">
            <table>
                <tr ng-repeat="actor in avengers.cast | filter:search">
                    <td>{{ actor.name }}</td>
                    <td>{{ actor.character }}</td>
                </tr>
            </table>
        </div>
    </div>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
<script>
    var myApp = angular.module('myApp', []);
    myApp.factory('Avengers', function () {
        var Avengers = {};
        Avengers.cast = [
            {name: 'Fabio',character: 'superman'},
            {name: 'whisher',character: 'spiderman'}
        ];
        return Avengers;
    });
    function AvengersCtrl($scope, Avengers) {
        $scope.filter = "name";
        $scope.search = {name:'', character:'', $:''};
        $scope.avengers = Avengers;
        $scope.change = function(){
            $scope.filter = $scope.mysearch;
        }
    }
</script>
</body>
</html>

Shoutout to @lopisan for the assistance! angularjs: change filter options dynamically

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

When the ng-click event is triggered, all other div elements within the ng-repeat that do not have the same $index value

My goal is quite similar to an accordion. In a simple explanation, I have an ng-repeat with an <a> tag that, when clicked, shows another div called "Printpanel" nested inside it using ng-show. Whenever the user clicks on another <a> tag, I wa ...

What are some creative ways to visually distinguish a TextField that is in readOnly mode?

I'm currently working on creating a form using the Material-UI library. I'm having difficulty figuring out how to distinguish my TextField when they are in readOnly mode versus edit mode. At the moment, they appear identical and I would like the ...

Populate tabulator table with nested data fetched through an ajax call

I received an API response from a store in JSON format containing three records at the first level. The structure of the response includes data, error_no, msg fields. Within the data field at the second level, I have data.items, data.total_pages, data.to ...

Execute a function before the page reloads in ASP.NET with the help of JQuery

Is there a way to call a function before postback in Asp.Net using JQuery? ...

Troubleshooting Port Issue When Deploying Node/Sequelize Application on Heroku

I am in the process of developing a Node/Postgres application that will be deployed to Heroku. During my attempts to launch the app in a production environment, I encountered a timeout error. According to Heroku, this error is likely due to database or por ...

JavaScript code to convert integers into decimal numbers

Currently, I am facing a challenge with my program that involves converting integers to binary and decimal. While the binary conversion is working fine, I am encountering difficulties with the decimal part. I am considering using the function intToFloat, b ...

The functionality of the Bootstrap dropdown list button is not functioning properly on mobile devices

Currently, I am in the process of developing a website and testing its mobile view on my iPhone. The website is still using bootstrap 3, but I have encountered some issues. When I tap on the navigation button on my iPhone, nothing happens - no dropdown lis ...

Can you provide guidance on implementing StyledComponents within the app folder of Next.js version 13?

Quoting information from the Next.js documentation: Attention: CSS-in-JS libraries that rely on runtime JavaScript are currently not compatible with Server Components. The following libraries are supported in Client Components within the app directory: s ...

Problem with displaying images and videos in a lightbox gallery

Currently, I am encountering an issue with the lightbox feature on my website. When trying to play a video, there seems to be a layer (div tag) blocking it, preventing me from playing or stopping the video. This problem occurs when clicking on an image fir ...

A guide on incorporating a customized Google map into your website

Recently, I utilized the Google Map editing service from this site: https://developers.google.com/maps/documentation/javascript/styling This link provided me with two things: 1. A JSON code 2. The Google API link However, I am unsure about how to incorpo ...

Learn more about how AngularJS uses the $q and $http services to manage promises

Regarding $http as described in the official documentation: The $http API is built on top of the deferred/promise APIs provided by the $q service. The $http service is a function that accepts a single argument - a configuration object - to create an HTTP ...

ng-if directive does not show data in AngularJS

I have a dynamic collection of images and videos that I want to display one at a time. Specifically, when I click on an image ID, I want it to show the corresponding image, and when I click on a video ID, I want it to show the relevant video. Below is the ...

Create a JavaScript object containing placeholders and another JavaScript object that holds the substitutions to be used

I have a placeholder object named ${var_name} { "name": "${title}", "description": "${description}", "provider": { "@type": "Organization" }, "hasInstance": [ ...

Saving Information Using Express-Session

Imagine you need a user to input their email and then save it to be accessible across multiple web pages. Would it be considered a poor practice to store this email in the session object of express-session? For example: req.session.email = '<user ...

Is there a way to split each foreach value into distinct variables?

I am looking to assign different variables to foreach values. I have fetched data from an API in JSON format, and then echoed those values using a foreach loop. My goal is to display the echoed value in an input box using JavaScript. I attempted the follow ...

Having trouble with the JavaScript function not working on page load

I'm currently working on writing JavaScript code that will run once the child page, created using the window.open function, has fully loaded. Despite trying methods like window.onload and window.setTimeout, I haven't had any success. I even expe ...

The corresponding Javascript method for jquery's ajaxStop

Currently, I have numerous ajax requests running concurrently and I would like to trigger a function once they all have completed. I came across the jQuery function: ajaxStop(), however, I am unable to utilize jQuery in this particular project. Is there ...

Having trouble passing an array from PHP to JavaScript

I'm facing an issue with the following code snippet: <?php $result = array(); while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){ $result[] = sprintf("{lat: %s, lng: %s}",$row['lat'],$row['lng']);} ?> <?php $resultAM = joi ...

The request for an advertisement was successful, however, no ad could be displayed as there was insufficient ad inventory available. Please handle the situation appropriately with the

Using react-native, I am trying to incorporate ads into my app but encountering an error. Despite attempting various solutions, nothing seems to work. It appears that the issue may lie with the AdMob Android SDK. While I have reviewed SDK videos related to ...

Harnessing Drupal's auto-complete values and events to dynamically adjust form elements based on search results

Although I'm not an expert in AJAX, Drupal, or Javascript, I'll do my best to articulate my question clearly. Currently, I am working with Drupal 7 on MySQL in a dev environment. I've created my own module called 'acid' to manage ...