Enhance text search functionality using AngularJS

Just starting to learn angularjs.

Below is the code I've written:

 $scope.styles = [{"name":"walking"},{"name":"Food"},{"name":"culture"}]

I have created a checkbox list

<div ng-repeat="style in styles">
 <input type="checkbox"> {{style}}
</div>

Currently, I am retrieving Tours packages with style values such as: walking ,food

$scope.tours = [{"Tourname":"sky walk","style:walking "},{"Tourname":"Accra markets","style":"food,walking"}]

The goal here is that when a style in the checkbox is clicked, only the tours with that specific style should be displayed.

Would appreciate any help or sample references!

Answer №1

Consider trying this approach: Utilize the ng-show directive along with a function to verify if a style has been selected.

function mainController($scope){
    $scope.styles = [{"name":"walking"},{"name":"Food"},{"name":"culture"}];
    $scope.tours = [{"Tourname":"sky walk",style:"walking "},{"Tourname":"Accra markets","style":"food,walking"}];

    $scope.selected=function(tour){
        for (var i = 0; i < $scope.styles.length; i++) {

            var style=$scope.styles[i];
            if(style.selected=="true" && tour.style.indexOf(style.name)>=0){
                return true;
            }
        }
        return false;
    }
}

Then, in the HTML:

<div ng-repeat="style in styles">
    <input ng-model="style.selected" ng-true-value="true" ng-false-value="false" type="checkbox"/>{{style}}
</div>
<h1>Tours</h1>
<div ng-repeat="tour in tours" ng-show="selected(tour)">
    <input type="checkbox"/>{{tour}}
</div>

For live demonstration, you can check out the Plunker link here.

Answer №2

Utilizing a filter is the best method for extracting specific data from a collection. To achieve this, you can implement a custom scope predicate function within a filter:

Scope Predicate Function:

$scope.hasStyle = function(item){
    return $scope.styles.some(function(style){
      if(style.selected && item.style.indexOf(style.name) > -1) {
        return true;
      }
    })
  }

Implementation in View:

<div ng-repeat="style in styles">
  <input type="checkbox" ng-model="style.selected">{{style.name}}
</div>
<div ng-repeat="tour in tours | filter: hasStyle">{{tour | json}}</div>

See Demo

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 it possible to create a "private" variable by utilizing prototype in JavaScript?

In my JavaScript code, I am trying to have a unique private variable for each "instance," but it seems that both instances end up using the same private variable. func = function(myName) { this.name = myName secret = myName func.prototype.tel ...

Having trouble decoding a cookie received from a React.js front-end on an Express server

When using React js for my front end, I decided to set a cookie using the react-cookie package. After confirming that the request cookie is successfully being set, I moved on to configure the Express server with the cookie parser middleware. app.use(cookie ...

Having trouble with the sleep function in nodejs?

Hey there! I'm currently working on a Node.js function that sends requests using array.map. However, I'm facing a challenge with making the function wait for 4 minutes when an error occurs before sending the next request. I've attempted to u ...

Nuxt - Issue persisting logged in state on refresh despite information being stored in local storage and cookies

I am facing an issue where the state gets cleared on refresh, even though the token, userid, user email, and expiration date are stored in local storage and cookies. I suspect there might be a problem with the store or something else needs to be done to re ...

When I try to use angular.injector.invoke, I am encountering an issue

As I was diving into learning angular, I came across a fascinating blog post that explained how we can access factories/services outside of controllers using angular.injector(). Excited to try it out, I attempted to implement this approach only to be greet ...

Call a function between two controllers by utilizing routeprovider

I have set up my route provider with AngularJS as shown below: var appModule = angular.module('ngLogin', ['ngRoute','restangular','btford.socket-io','ngSanitize','xeditable']); appModule.config( ...

effective methods for setting up live reload feature for an Angular application

I've been attempting to implement grunt livereload for a basic Angular application. Below is the section from my gruntfile: watch: { livereload: { files: [ '*.{html,js}', & ...

The Splitter remains inactive until a peculiar series of actions is taken

Trying to troubleshoot this issue with a library called Split.js, which can be found here: https://github.com/nathancahill/Split.js I've encountered an interesting problem where I have to disable the height CSS property of my container, move the spli ...

Leveraging Laravel 5.4 routes with AngularJS $http module

I'm working with Laravel 5.4 and AngularJS. Currently, I have a function set up like this: $scope.allPosts = function() { $http.get("/posts") .then(function(){ }, function(error){ }); }; Is there a way for ...

What is the process of permanently modifying an HTML document using JavaScript?

I'm interested in creating a basic comment section using JavaScript. Here is the structure of the form : <form> <textarea cols="50" rows="10" placeholder="Share your thoughts ..." id="theComment"></textarea><br/> < ...

Why would you need multiple root handlers?

One interesting feature to note is that multiple callback functions can be used as middleware to handle a request. These callbacks can take on different forms - they could be in the form of a single function, an array of functions, or even a combination of ...

A more concise validation function for mandatory fields

When working on an HTML application with TypeScript, I encountered a situation where I needed to build an error message for a form that had several required fields. In my TypeScript file, I created a function called hasErrors() which checks each field and ...

The process of eliminating line breaks in javascript is not functioning as expected

I've been searching all over the place, experimenting with different methods, but I just can't seem to fix this issue.. var save_field = res[0]; var save_value = res[1]; save_value = save_value.replace(/\n/gm, '<br />'); con ...

Utilizing React JS to dynamically populate a table with data from an external JSON file

As a newcomer to the realm of React, I am facing challenges in displaying my JSON data in a table. class GetUnassignedUsers extends React.Component { constructor () { super(); this.state = { data:[] }; } com ...

What is the best way to implement a switch case with multiple payload types as parameters?

I am faced with the following scenario: public async handle( handler: WorkflowHandlerOption, payload: <how_to_type_it?>, ): Promise<StepResponseInterface> { switch (handler) { case WorkflowHandlerOption.JOB_APPLICATION_ACT ...

Is it possible to have two router.js files within a single Angular project?

Encountering a dilemma in my Angular UI routing project with rendering the view. Contemplating using two router.js files. Is it feasible to include two router.js files in one project? What drawbacks might arise from this approach? ...

The Spotify Whitelisted URI may show an error message: { "error": "invalid_grant", "error_description": "Redirect URI is invalid" }

Although there are similar questions out there, I'm facing a different issue. I am trying to obtain an access token from Spotify API, but all I keep getting is the dreaded "invalid redirect uri" error. Below is my API call: const request = require(& ...

Creating a dropdown menu for an extensive list of 100 menu items: a step-by-step guide

In my React JS front-end project, I have implemented a drop-down menu using Material-UI. Currently, the menu items are hardcoded which works fine for a small number of items. However, this approach becomes cumbersome when dealing with a larger number of ...

Utilize AngularJS ng-repeat directive to refine JSON objects

I'm working on an angular js controller with a json array that organizes countries by continents. Each continent consists of its own array of countries. //CONTROLLER app.controller('CountryController', function(){ this.continents = ...

Angular dynamic calculations for min and max values result in an unusual user interface

I am encountering an issue with a datetime-local input field that has max and min attributes. <input type="datetime-local" ng-model="model.date" min="{{min}}" max="{{max}}"> These attributes are dynamically set based on the date from another input ...