Sending information to the model within the ng-click event

Currently, I have a system in place where all articles from the database are displayed, along with a text search feature for easy navigation.

<input ng-model="searchText" placeholder="Search for articles" class="search-text">

I am utilizing this searchText to filter out relevant content within the database.

<section class="articles" ng-repeat="contentItem in content | filter:searchText">

My next goal is to implement buttons that represent categories and tags from the database. These buttons should allow users to instantly filter content based on their selections.

<span ng-repeat="category in categories">
  <button ng-click="searchText = '{{category.local.name}}'" class="btn btn-primary">{{ category.local.name }}</button>
</span>

The current implementation isn't functioning as expected. However, if I manually input the categories without using ng-repeat, it works fine:

<span>
  <button ng-click="searchText = 'some text'" class="btn btn-primary">Some text</button>
</span>

My main query revolves around finding an efficient way to pass both the search input and button values to the filter method effectively.

For reference, here is the complete code snippet:

<div class="container">
 <h1>List of articles</h1>
<section class="search-items">
<input ng-model="searchText" placeholder="Search for articles" class="search-text">
<div class="row">
  <div class="col-sm-6">
    <h6>Search based on categories:</h6>
    <span ng-repeat="category in categories">
      <input type="button" ng-click="searchText = '{{ category.local.name }}'" value="{{ category.local.name }}" class="btn btn-primary">
    </span>
  </div>
  <div class="col-sm-6">
    <h6>Search based on tags:</h6>
    <span ng-repeat="tag in tags">
      <input type="button" ng-click="searchText = '{{tag.local.name}}'" value="{{ tag.local.name }}" class="btn btn-primary">
    </span>
  </div>
</div>
</section>
<section class="articles" ng-repeat="contentItem in content | filter:searchText">
  <article class="well">
    <h3>{{ contentItem.local.title }}</h3>
    <p>{{ contentItem.local.content }}</p>
    <span><b>Article author: {{ contentItem.local.author }}</b></span><br/>
    <span class="label label-primary">{{ contentItem.local.categories.category }}</span>
    <span class="label label-primary">{{ contentItem.local.tags.tag }}</span>
  </article>
 </section>
</div>

Answer №1

angular.module('myApp', [])
.controller('ThingsController', function(){
  var ctrl = this;
  ctrl.things = ['thing 1', 'thing 2', 'another thing']
  ctrl.searchText = "something"
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular.min.js"></script>
<div ng-app="myApp" ng-controller="ThingsController as thingCtrl">
<div ng-repeat="thing in thingCtrl.things">
  <button ng-click="thingCtrl.searchText = thing">{{thing}}</button>
</div>

<pre>{{thingCtrl.searchText}}

The code snippet above demonstrates the functionality using the controller as syntax. It is recommended to avoid using $scope as your model. Instead, ensure it points directly to your model to prevent potential prototypical inheritance issues. For example, use $scope.myModel = {someProp:4} rather than $scope.someProp = 4. By using the controller as syntax, these problems can be easily avoided.

Learn more about scope prototypal / prototypical inheritance nuances in AngularJS

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

As you scroll, this smooth marquee effect gently shimmers with each movement

I've been trying out this code to create a scrolling marquee text, but the issue is that after 7000 milliseconds it starts to jitter, which doesn't make the text look good. Any suggestions on how I can fix this problem? Let me know! <script ...

How to extract specific words or numbers from a text using cheerio JS

I am curious about how to extract all the sets of numbers that appear after "id": on every line from this URL using Cheerio in JavaScript: For example: [{ "id": 19437838336128, "product_id": 2069464547456, "title": "3", "price": "110.0 ...

Searching for a streamlined approach to sending out numerous HTTP requests in a node.js environment

I'm new to the world of JS/node.js after working with .Net. I have an existing Web API host that I want to stress test with different payloads. I am aware of load testing tools available for this purpose, but my focus right now is on finding an effic ...

Angularjs directive experiencing intermittent firing of IntersectionObserver

Currently, I am in the process of integrating lazy loading using the IntersectionObserver within my angularjs application. However, there seems to be an issue where the callback function of the observer is not always being triggered when scrolling up and ...

Concealing a button in Odoo Helpdesk with JavaScript: a step-by-step guide

For Odoo version 15, I have implemented a JavaScript code that is triggered by the buttons "Accept" and "Deny" in a boolean field within the res users model. The functionality works as expected, however, my current issue is that both buttons appear on the ...

What steps should be taken to refresh a page following an AJAX file upload?

I need some help creating a progress bar to track file uploads on my website. Here's what I have so far: HTML: <form action="upload/files.php" method="post" enctype="multipart/form-data" id="frmUpload"> <input type="file" name="upfile" ...

Leveraging the ASP.Net Ajax framework for seamless Xml manipulation across different browsers

Currently, I am in the process of updating a web application that utilizes ActiveX objects in client-side code to manipulate XML data. Unfortunately, this app is only compatible with Internet Explorer and I need to make it work across all browsers. I am s ...

I am looking to create a rounded circular progress bar with smooth edges

I'm looking to create a circular progress bar with rounded edges on the highlighted segment, similar to this example: https://i.sstatic.net/kNKyzm.png While I've managed to create a basic version, I'm struggling to achieve the rounded ends ...

The tilesloaded event in google.maps.event.addListener is unexpectedly failing to trigger

Today, while testing popover messages on my cordova/ionic app, I compiled the app and noticed that the maps weren't loading. Instead, only my custom "Loading map..." spinning icon kept showing. Upon investigating further, I found that var setMap = n ...

Embedding an Angular 6 application as a JavaScript file in a pre-existing HTML website

Is it possible to seamlessly integrate an Angular 6 application into an existing HTML site by including it as a single JS file? Can you provide some insights on how to bundle an entire Angular App into just one JS file? Appreciate any help or tips. Thank ...

Struggling with coding an array of images in Angular JS

I am having trouble displaying the images as thumbnails and full images for each "gem." The Angular tutorial I followed did not provide enough detail on how to do this. Here is my HTML code: <!DOCTYPE html> <html ng-app="store"> <head> ...

Guide to dividing a string and structuring it into an array

I need help breaking apart these strings: var str = '(john) the quick brown (emily) fox jumps over (steam) the lazy dog.' var str1 = '(john) the quick brown fox jumps over (steam) the lazy dog.' to create an array like this: joh ...

Saving the state of a Kendo UI Grid in an AngularJS application

I'm encountering an issue with loading the saved state of the grid in Angular. Here is the HTML for the grid: <div id="grid" kendo-grid k-options="GridOptions" k-ng-delay="GridOptions"></div> After making an Http call and filling in th ...

Exploring new options to deduct time from Kendo UI timepickers without relying on Javascript

My current project involves an Asp.net MVC 4 application that includes a Time entry screen. This screen utilizes various Kendo controls and Razor Html helpers to enhance the user experience, such as: @(Html.Kendo().TimePickerFor(m => m.StartTime).Name( ...

Creating a new webpage with a custom URL in a React application

After receiving an HTML file from the server, the application displays the data (responseToPost) on the page using the following code: <div dangerouslySetInnerHTML={{ __html: this.state.responseToPost }} /> I am interested in creating a new URL wher ...

In the event that the `algorithms` option is not defined, an error will be thrown stating that `algorithms` must be specified: `Error: algorithms should be

Currently, I am diving into the world of Nodejs, but I have hit a roadblock in my learning journey. I recently installed a new library from npm called express-jwt, but it seems to be throwing an error when I try to run it. Below is the snippet of my code a ...

A beginner's guide to using Jasmine to test $http requests in AngularJS

I'm struggling with testing the data received from an $http request in my controller as I don't have much experience with Angular. Whenever I try to access $scope, it always comes back as undefined. Additionally, fetching the data from the test ...

YUI: Personalizing the message displayed in the browser when cancelling a window close event

I am working on a YUI application that requires me to notify the user before closing the window in certain situations. To achieve this, I have implemented a function to capture the window close event: onWindowClose: function(e) { if (...) ...

In the link function of a custom directive in Angular, the curly braces {{}} are processed as

Can you provide guidance on interpreting the content of a div where my directive is used as an attribute? For example: <div my-directive>{{1+1}}</div> My link function is as follows: link = (scope, element, attrs) => interpretedString ...

How can I transfer data from a C# code to a JavaScript file in asp.net?

I am faced with the task of transferring values from a C# class to a JavaScript file. To achieve this, I have generated a string in C# which contains the values of the list as follows: count = 0; JString = "["; for(i=0; i<x; i++) { JString += "{Sou ...