Update the input field in the controller to act as a filter supplier

I currently have an input text field displayed in my view:

<input type="search" placeholder="Search" ng-model="search.$">

This input field acts as a filter for the list of items displayed:

<a ng-repeat="item in items | filter:search" href="#">{{item.name}}</a>

The reason I use search.$ is to enable searching through all properties of the object item.

Now, I am looking to set the input value programmatically from the controller whenever needed:

angular.controller('MyCtrl', function ($scope) {
  var query;
  $scope.updateSearchQuery = function () {
     //query is populated from another source, service, http provider...
     $scope.search = query;
});

However, even though this new query filters the list, it does not display in the input field.

I've attempted using $scope.apply without success:

...
$scope.$apply(function() {
  $scope.search = query;
});
...

UPDATE: Another method I tried was:

$scope.search.$ = query;

You can find a demonstration here: http://plnkr.co/edit/CwzsrJxU9Kb9AARVcENT?p=preview

Can you identify what I might be overlooking or missing?

Answer №1

Avoid using a dollar sign ($) as a property name in Angular, as it may get stripped internally by Angular when used in functions like jsonFilter.

If you need to filter an array by all properties, there's no need for a variable starting with '$' in your search object. Here's a corrected version of the example:

PLUNKER

angular.module('MyApp', [])
.controller('MyCtrl', function ($scope) {

  $scope.search = {
    query: ''
  };

  $scope.updateSearchQuery = function (query) {
    $scope.search.query = query;
  }

  $scope.items = [
    {
      id: 'someid',
      name: 'John'
    },
    {
      id: 'someotherid',
      name: 'Smith'
    },
    {
      id: 'anotherid',
      name: 'Patrick'
    }
  ];

});
<body ng-controller="MyCtrl">
  <input type="search" placeholder="Search" ng-model="search.query">
  <button ng-click="search.query=''">Clear</button>
  <a style="display:block" ng-repeat="item in items | filter:{$: search.query}" href="#">
    {{item.id}} | {{item.name}}
  </a>

  <button ng-click="updateSearchQuery('John')">Set Filter to "John"</button>
  <button ng-click="updateSearchQuery('some')">Set Filter to "some"</button>

</body>

Also, note that $scope.search.$ = query; won't work if $scope.search is not initialized beforehand.

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

Obtain the ID of a YouTube video from an iFrame link using jQuery

Check out this YouTube video: iframe width="560" height="315" src="//www.youtube.com/embed/XbGs_qK2PQA" frameborder="0" allowfullscreen></iframe>` (Hell Yeah! Eminem :P) I only want to extract "XbGs_qK2PQA" from the link provided. Using $(&apo ...

Video Playback Issue: Unable to Pause on Final Frame When Looping is Turned On

Having trouble pausing a video on the very last frame when the video is already on the final frame. var app = angular.module('myApp', []); app.controller('MainCtrl', function ($scope) { }) app.directive('someVideo', func ...

The content within my "div class=content" is intersecting with the nav-justified section

My login page features a nav-justified list that allows users to connect using either a login/password or guest mode. However, I have encountered an issue where clicking on "Login" still displays the option for "Guest," and if I click on "Guest" again, it ...

AngularJS Perspectives: Unveiling the Secrets of Successful Implementation

Do you have any tips on troubleshooting AngularJS views? I found a demo at AngularJS: ngView, but the provided jsfiddle doesn't seem to work. I've been trying to play around with it, but still haven't had any success. This is the code I&apo ...

Only one method failed the CORS Pre-Flight

I’m currently facing a unique issue with my Ionic app and ASP.NET Web API backend. I addressed pre-flight CORS problems early on by configuring my WebApiConfig class as follows: config.EnableCors(new EnableCorsAttribute("*", "*", "*")); For a while, ev ...

The issue with CSS filter invert not functioning properly in Mozilla Firefox is causing complications

I am currently developing a small Firefox add-on designed to make reading pages at night more comfortable. The goal is to invert page colors without affecting images. Here is the code snippet I am using: document.body.style.filter = "invert(100%)"; var i ...

Fade effect button with jQuery on mouseover

I have implemented a mouseover fade effect button using jQuery. However, I am facing an issue where the image fades to white instead of "img.b" as intended. Can anyone provide suggestions on why this may be happening? $(document).ready(function(){ $(" ...

Combining JSON arrays into a single multidimensional array

I have received the following JSON data from an API, and unfortunately, I do not have control over its format. Hence, changing the format is not feasible for me. I am facing difficulty in combining this JSON data into a single JSON array. My goal is to pr ...

Displaying selected checkbox values in a URL with parameters using PHP and JavaScript

I am looking to extract the selected checkbox value and append it to the browser URL with a parameter name. Below is my HTML code: <div style="width:200px; float:left"> Price <div> <input type="checkbox" name="price" value="0-1 ...

Rails offers a unique hybrid approach that falls between Ember and traditional JavaScript responses

My current project is a standard rails application that has primarily utilized HTML without any AJAX. However, I am planning to gradually incorporate "remote" links and support for JS responses to improve the user experience. While I acknowledge that gener ...

Locate the index within the array that satisfies a given condition for the value contained in

Upon receipt from the server, the client is processing a message through socket.io. The content of this message contains an object with the following structure: { from, text, dateTimeSent, chatId } This information pertains to a specific ...

Having trouble loading a model converted from FBX to JSON using THREE.JSONLoader

I recently converted an FBX model to JSON using a Python script called convert-to-threejs.py. However, I am encountering issues trying to load it into three.js (r58). An error message stating "Uncaught TypeError: Cannot read property 'length' of ...

Angularfire: how synchronized arrays behave

Recently, I've encountered some issues with synchronized arrays in AngularJS using AngularFire. My setup includes angularfire 1.1.3 and firebase 2.3.1. I initialized the query like this: var arr = $firebaseArray(ref.limitToFirst(5)); Initially, when ...

Is it possible to implement multiple boolean filters in Angular?

Within a user's settings node, there are three boolean values that match those found in an item. I am attempting to filter the list of items based on the user's display preferences. I have scoured high and low, but haven't found a solution ...

Ensuring the capture of all errors within asynchronous express route handlers using async-await syntax

Imagine having a route set up like this: app.get('/malfunction', (req, res) => { throw new Error('Malfunctioning!'); }); In this case, no response will be sent to clients. However, you can include a middleware for handling all ...

Fetching parent records and their associated children with a single Parse REST API request

Currently working on a small application, my first task involves making a call to Parse's REST API using AngularJS's ngResource. I've managed to create two Parse classes ("Parent" and "Child") and established a many-to-many relationship bet ...

Interacting between AngularJS controllers located in separate files creates seamless communication within the application

I am facing a situation where I have two controllers in separate files, one in file a and the other in file b. Whenever the controller in file a performs an action, I need it to either call a function or trigger the controller in file b. Is there a way to ...

What is the correct way to update an empty object within the state using setState?

I'm currently dealing with a state that looks like this: this.state={ angles:{} } I need to know how to use setState on this empty object. Specifically, if I want to add a key and value inside my empty 'angles'. How can I achieve that? Fo ...

Ensure that the keyboard remains open in an Ionic chat app when a button is clicked

Having some trouble with my Ionic v1 chat application. Everything is set up, but I'm running into an issue where clicking on the send button causes the keyboard to lose focus from the input and then close. I've tried several solutions, but none ...

Preserving Selected Dropdown Options After Form Submission

My PHP form consists of 7 fields, with 6 of them being required. One of the mandatory fields is an age dropdown that I'm filling in using JavaScript. The issue I'm encountering is that when a user enters information for 5 out of the 6 required f ...