Populate the keyword search filter with a predetermined term in Angular JS

I'm facing an issue while trying to pre-fill a value in an input field on a page. Although the page loads with the value, it doesn't trigger any filtering until I manually enter something. Is there a way to make the filtered results load automatically when the page loads?

As a newbie to Angular JS, I would really appreciate any guidance or assistance in the right direction.

So far, I have attempted:

Adding

ng-init="search.keywords='initial'"
to the input tag, but it didn't result in any filtering.

Also, using

$scope.search = { keywords: 'initial' };
did set the initial value, but again, no filtering occurred.

<input type="text" id="search-keywords" ng-model="search.keywords"
       class="form-control" placeholder="Keyword search">
$scope.$watch("search", function (newVal, oldVal) {
    if (newVal) {
        $scope.doFilter(newVal);
    }
}, true);

$scope.doFilter = function (search) {
    // Filtering logic here
};

$scope.filterByKeywords = function (courses, keywords) {
    // Keyword filtering logic here
};

Your help in resolving this issue would be highly appreciated!

Answer №1

The $watch function is essential for detecting any changes in the input field once it has been loaded into the DOM.

To ensure it works correctly the first time around, you have a couple of options:

One option is to use ng-init on the element to trigger the filter method upon DOM load.

ng-init="doFilter(search)"

Alternatively,

You can call the filter function once at the controller level before the actual watch begins.

$scope.search = { keywords: 'initial' }; 
$svope.doFilter($scope.search);

Answer №2

To specify the function that needs to be run when the page loads, you can use the ng-init directive and define it like this:

ng-init="doFilter({criteria: 'initial'})"

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

NextAuth: strategies for handling custom errors without triggering a redirect

I am exploring ways to use NextAuth with username and password credentials, but I am struggling to find a way to send custom errors back to the client side. It appears that I can only return a 200 ok response or redirect to an error page from the authorize ...

What are the best tools to develop a browser-based 2D top-down soccer simulation?

I'm looking to create a 2D top-down soccer simulation game for web browsers using modern technologies and without the need for additional plugins like Flash or Silverlight, making it compatible with mobile devices as well. The game will be AI-controll ...

Could integrating Firebase as the bridge between AngularJS and NodeJS be considered a less than optimal choice?

Seeking input on the design of a system I am constructing. Currently, I have several Node.JS scripts updating a Firebase DB, with front-end AngularJS apps retrieving data from the Firebase DB. This setup is functioning effectively. Now, I am looking to ...

Node.js socket.io emit function not functioning properly

In my current configuration, I have the following setup: app.set('port', process.env.PORT || 3000); var httpserver = http.createServer(app).listen(app.get('port'), function(){ console.log('Express server listening on port ' ...

Exploring nested routes with React Router 4

When a user clicks on an image, the URL changes to ("/r/:id") but the content of the page remains unchanged. <BrowserRouter> <Switch> <Route path="/r/:id" component={View} /> </Switch> </BrowserRouter>, <Link ...

Comparing front end automation between JavaScript and Java or Ruby

Could you provide some insights on why utilizing a JS framework like webdriverio is preferred for front end automation over using Selenium with popular languages like Java or Ruby? I understand that webdriverio and JS employ an asynchronous approach to fr ...

Issue with formatting data correctly in JSON file while using Express.js

I am facing an issue with loading data from a JSON file into an array in the correct format: var jobs = [ { ID: 'grt34hggdggf', Employer: 'A1', Title: 'tobi1', Location: 'Los Angeles, CA', Department: 'depart ...

Tips for accessing information from the Redux store

Seeking to retrieve data about the businessName within the Organization, located in the payload of the user. I attempted this method but with no success. const { user } = useSelector((state) => state.auth); <Text mt={3} fontSize="20px" fon ...

Submitting jQuery Ajax forms multiple times using the POST method

After trying various solutions for this issue, none seem to effectively address my problem. Here are some examples: $("form#sending-notice-form").unbind('submit').bind('submit', function (e) { e.preventDefault(); .. }); While ...

Cease the continuous scrolling of the display element now

I'm having trouble with my progressbar animation when scrolling. It seems to run multiple times instead of just once. I apologize if there's an error in my code. Could someone please assist me? This is the code I am using: <div class="demo- ...

Command for setting AFK status using quick.db and checking if it's working

I have been struggling for a while to get this command working. I am trying to make it display the author's status as "trying a fix". I'm not sure if quick.db is the right solution for this, but I've attempted to save the author's stat ...

Switch between selected boxes in AngularJS

I am currently working on a feature where all boxes should be automatically checked when the user deselects them both. Just to clarify, there are two items in cards as shown in the image. These cards are initially selected. When the user deselects the fir ...

Error in Angular 1.6 caused by binding issues

Just started using Angular and encountering this issue. Error: Uncaught TypeError: Cannot use 'in' operator to search for '$ctrl' in subpackage I have a parent component and a child component where I have defined a function in the par ...

Adding firebase analytics to your NextJS app in the right way

My react/nextjs app includes a firebase.js file that looks like this: import firebase from 'firebase/app' import 'firebase/auth' import 'firebase/analytics' import 'firebase/firestore' const firebaseConfig = { api ...

The Protractor identifier for the dynamically generated element

Is it possible to locate an element using a partial id? The page I am testing has a dynamic id where the first part contains a variable number, making it difficult to predict the complete id beforehand. ...

Rendering external HTML content within a React component can be achieved by utilizing parsing techniques

In my React application, I have a component that receives HTML content as a string field in the props from an API call. My objectives are: To render this HTML content with styles applied. To parse the content and detect "accept-comments" tags within sec ...

What sets apart window.location.href from this.router.url?

I'm curious about the various methods of obtaining the current URL in Angular. For instance: this.router.url My main question is: What advantages does using this.router.url offer over simply using window.location? Could someone kindly provide an exp ...

Difficulty Parsing Date within XLSX File Using SheetJs

When attempting to read an XLSX file using the sheetjs node-module, I encountered a problem with dates in one of the columns. The original data in the file is formatted as '2/17/2020', but after parsing it through xlsx, the format changes to &apo ...

Dragging the mouse outside of an element after clicking inside

I've come across a common issue, but unfortunately haven't been able to find a solution yet. window.onload = function (e) { var foo = document.getElementById('foo'); foo.addEventListener('click', function(e) { ...

When assessing a list against an array of objects in JavaScript

I am currently working on some Angular code with the objective of minimizing the use of Angular 1.x functionality, as it will be refactored in the near future. My task involves comparing an array: let subscription = [ "Cinemax Subscription", "Disn ...