Send the text of the element to an AngularJS controller

Currently, I am attempting to extract the text inside a <p> element within my Angular application and pass it on to both a method and a view using ng-route. The objective is that when a user clicks on the <p>, the innerText will be sent through a method, fetch some data in return, and eventually display a new view containing the response data.

<p ng-click="searchUser()">Bob Ross</p>

JavaScript code:

var app = angular.module('app', ['ngRoute'])
  .config(['$routeProvider', function($routeProvider){
  .when('/searchUser:name', { 
        templateUrl: 'user-results.html',
        controller:  'searchController'
    })

app.controller('searchController', function($scope, $routeParams) {
    $scope.name = $routeParams.name;
    $scope.searchUser = function(){
        // do some stuff;
    }
});

I am currently unsure about the correct approach to capture the inner text of the <p> tag accurately and then passing it through the method (I might be missing the mark completely); should I bind it to my model first and then send it as a routeparam?

Your assistance on this matter would be greatly appreciated!

Answer №1

Assuming that you are utilizing the $http service to retrieve the user list within your controller, you can implement the following solution:

<div ng-repeat="user in users" ng-click="searchUser(user.name)">{{user.name}}</div>

Then, in your controller:

$scope.searchUser = function(userName) {
   // Perform actions with userName
};

Answer №2

If you pass the $event parameter to the findUser function, you can access the element using $event.currentTarget. To learn more about the $event object, check out this link.

<div ng-click="findUser($event)">John Doe</div>

$scope.findUser = function($event){
    var user = $event.currentTarget.innerHTML;
}

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

React app experiencing freezing due to custom asynchronous function utilisation

I am currently facing an issue with my personal project where the application freezes under certain circumstances. The initial load works fine, but when I make changes to the code causing React to re-render, the app just freezes. It seems to be related to ...

Ways to verify if information is being added to a JSON file or not

JSON Here is the JSON structure where I am adding data with a button click event. var myData = { "info" : [] }; JavaScript Function I have written this function to add data to the JSON object: myData.info.push({ "Name" :name, ...

Exploring jQuery's selection techniques involving filtering and excluding elements

How can I select all elements with the class .Tag that are not equal to the element passed to the function? Here is my current attempt: $("a.tag").filter(":visible").not("\"[id='" + aTagID + "']\"").each( function place(index, ele ...

Updating a specific array element in MongoDB by its id

I've been attempting this task since yesterday without success. I have two distinct Schemas - the User Schema and the Vital Signs Schema. The Vital Signs Schema is nested inside the User Schema as an array. My goal is to modify a specific vitalSigns ...

Exposed function in JavaScript vulnerable to exploitation

In my application, I have a JavaScript function that redirects users to the login page after a minute: (function redirect_expired() { $j.get('/app/ExpiredSession', function (resp) { if (resp && resp.redirectTo) { ...

Error encountered: Index 109 - The function $.ajax(...).success is not recognized as a valid function while working with jQuery in a Node

I'm just starting to learn about jquery and have been experimenting with ajax in my recent code. Below is the snippet of what I have implemented: $(function(){ $("#status").change(function(){ if($(this).is(':checked')) ...

Ways to include scrolling specifically for one template

As a newcomer to frontend development, I have recently started learning Vue and the Quasar Framework. I am currently working on a table and trying to set a fixed table name with only the table items scrollable. <template> <q-table virt ...

Looking to manage the query string "/projects?technologies=AI&industries=Security" within a Node.js environment

I am new to creating a query string parameter and could use some assistance. I am looking to filter data based on the JSON fields 'technologies, industries, and maturity', each of which has an array of elements that I want to filter. Here is the ...

Establishing Routing for Angular within an ASP.NET Web API 2 application

Currently, I am facing difficulties in setting up the routing for my project. There are several cases that need to be handled, but I am struggling to make them work as intended. case 1: / - Should route to the index of the angular app Case 2: /{angular ...

Add information to the <script> tag

There is a row that I sometimes clone. <script id="SubRow10" type="text/template"> <select id="SubSelect10" class="form-control" name="SubcategorySelect" required> <option value="m,2">Op1</option> <option value="m,3"&g ...

What is the process for importing JSON from an NPM package in Angular version 15?

I've been dealing with a local package that contains a json file, and my current challenge is to load this json file into the Angular 15 app.component.ts. To bring the json file package into my Angular project, I followed this installation process: n ...

Issue with Bootstrap tool tip not functioning inside modal form label tag

Is it possible to have a hover-over tooltip associated with text inside a label tag? I seem to be having issues with this implementation. When I move the tooltip outside of the label, it works fine. Below is the code snippet in question: <div class=&quo ...

In PHP, validating a value stored in a database against one entered in a text box

My form consists of multiple text fields, with the number determined by the amount of data in a database. Both inputs are integers. I would like to set up a validation where an error is triggered if the inputted value exceeds the corresponding value in t ...

Strategies for Handling Logic in Event Listeners: Choosing Between Adding a Listener or Implementing a Conditional "Gatekeeper"

What is the most effective way to manage the activation of logic within event listeners? In my experience, I've discovered three methods for controlling the logic contained in event listeners. Utilizing a variable accessible by all connected sockets ...

jquery allows you to toggle the visibility of content

There are two divs with a button positioned above them. Initially, only one div, the catalogusOrderBox, is visible. When the button named manualButton is clicked, it should display the manualOrderBox div while hiding the catalogusOrderBox div. The text on ...

What is the best way to employ TypeScript for passing parameters to JavaScript functions that utilize the arguments object?

Using Angular 8 at the moment and attempting to implement a script from someone else. However, I am facing an issue due to my lack of knowledge in this area. The function in the javascript operates like this: window.X = function() { var e = argument.l ...

Mastering the art of utilizing $.get(url, function(data) in pure JavaScript

I am currently exploring how to achieve the equivalent of $.get(url,function(data) { code }; in pure JavaScript. function fetchImage(keyword){ if(!ACCESS_KEY){ alert("Please update your access key"); return; } var request = new XMLHttpRequ ...

Discover the two words before and after a span element using jQuery

data-color="red"I am looking for 2 words before and after the span tags. Here is the html code: <p>This pathway has an inner and an outer wall. The pressure <span data-color="red" class="highlight">inside the</span> eye closes the tun ...

Refreshing the connected value of an input upon making changes

I'm currently developing a simple to-do application. Each task is included in an input item within a Vue component called <list-item>. These <list-item> components are generated using a v-for directive that points to an array of tasks. Th ...

Once the hidden DIV is revealed, the Youtube video within it begins to load

I currently have a hidden DIV on my website that contains a YouTube clip. My goal is to load the video in the background once the page has fully loaded, so that it's ready to play when the user clicks the button to reveal the DIV. However, at the mo ...