What is the best way to choose "this" element in Angular?

Within my template, I have 5 buttons each utilizing the same ng-click function. These buttons essentially function as a tabbed navigation system, where clicking on one button directs the user to that specific tab's content pane. All of these buttons can be duplicated and are enclosed within a template structure. Similarly, the tab panes exist within another template but remain inactive until a user clicks on a button to activate them. This setup involves multiple nested click functions which perform various actions based on the user's interaction.

In jQuery, I could easily select the clicked object using "this" and manipulate it accordingly. However, achieving the same functionality in Angular seems to be more challenging. Currently, when a button is clicked, the action is applied to all buttons simultaneously. While creating separate functions for each button could address this issue, I am seeking a more scalable solution.

To summarize:

  • Is there a way to replicate the functionality of selecting "this" in Angular?
  • I prefer a solution that exclusively utilizes Angular without incorporating jQuery.
  • How can I efficiently manage nested click functions in this scenario?

    <nav class="block--menu">
    <section class="content--menu" ng-controller="ActiveCtrl">
        <div class="menu" >
            <button  class="menu__item" ng-click="showConfirm()"></button>
            <button  class="menu__item" ng-click="showConfirm()"></button>
            <button  class="menu__item" ng-click="showConfirm()"></button>
            <button  class="menu__item" ng-click="showConfirm()"></button>
            <button  class="menu__item" ng-click="showConfirm()"></button>
        </div>
    </section>
    

Answer №1

To access the jQuery event object in Angular events, you can use $event. For more information, please refer to the documentation. However, if you find yourself passing this object to your controller, it may indicate that you are not following the best practices recommended by Angular.

Here is how you can use it:

<button  class="menu__item" ng-click="showConfirm($event)"></button>

And this is how you handle it in the controller:

$scope.showConfirm = function($event){
    //$event.target should be your link
};

Answer №2

It's time to shift your mindset away from jQuery and avoid direct manipulation of the DOM. Embrace a more Angular approach where your controller focuses on data manipulation, leaving the view to reflect these changes. When you adopt the Angular way, your code will typically resemble the following:

HTML

<section ng-controller="ActiveCtrl as ctrl">
    <div class="menu" >
        <button ng-repeat="button in ctrl.buttons track by $index"
                ng-click="ctrl.showConfirm(button)"
                ng-class="{'menu__item_active':button.active, 'menu__item':true}"
        >{{button.name}}</button>
    </div>
</section>

JavaScript

angular.module('app',[]).
  controller('ActiveCtrl', ['$window', function($window) {
    this.buttons = [{
      name: 'First'
    }, {
      name: 'Second'
    }, {
      name: 'Third'
    }];
    this.showConfirm = function(button) {
      button.active = !button.active;
      $window.alert(button.name);
    }
  }]);

Plunker

http://plnkr.co/edit/Dg10cXqFxEKgEt7jWQ7Z?p=preview

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 a 'Virtual DOM' included in React Native's architecture?

According to the ReactJS wiki page on Virtual DOM: React uses an in-memory cache of data structures to efficiently compute differences and update the displayed DOM in the browser. This allows developers to write code as if the entire page is re-rendered ...

Dynamically loading iframes with JQuery

I have implemented a jQuery script to load another URL after a successful AJAX request. $(document).ready(function() { var $loaded = $("#siteloader").data('loaded'); if($loaded == false){ $("#siteloader").load(function (){ ...

Avoid filling the container with an excessive amount of grids while maintaining the correct aspect ratio

I encountered a situation where I needed to dynamically create a grid with square grids of dimensions MxN. Below is the code snippet for achieving this: rerender = (event) => { const height = document.getElementById("y-input").value; const width ...

Using Javascript's document.write function to modify the content of a PHP page

Here is a Javascript function that capitalizes the first letter of a string: function capitalizeFL(string) { return string.charAt(0).toUpperCase() + string.slice(1); } In a file named statuswindow.php, there are PHP scripts that use this function to ...

Retrieving Information from JSON File Using a Variable (JavaScript/Discord.js)

While I was coding my Discord bot, I encountered an unexpected issue. Normally, after linking a JSON file, you can access data by using jsonFile.path to retrieve specific information. However, I faced a challenge where I needed to replace the path with a ...

Is there a way to find the TextArea element on Facebook's home page using a Selenium locator? Could it possibly be using jQuery

Sign in using any of our Facebook login details. Upon successful login, you will be directed to the page below. Query: Can you spot the "What's on your mind" or "continue to post" text box? I need to find the text box, input text, and then click on ...

Sharing and displaying images on Sails JS platform

Using Sails JS, I am attempting to upload an image and display it in a view. Queries: The uploaded image is located in .tmp/uploads, how can I retrieve it from a view? Is there a method to access the uploaded image? The image's name is altered in ...

JavaScript allows users to create a single string by merging multiple strings positioned at various points

Let's say we have 3 strings: s1 = "ab", s2 = "cd", s3 = "ef". The task is to form a new string by merging s1, s2, and s3. The twist here is that the user has the freedom to choose the positions of these 3 strings. For example: s1 - position 3; s2 - ...

RegEx: determining the smallest sum of digits required in a character sequence

I'm trying to figure out a way to count the number of digits in a string that resembles a password. Currently, I am using this regular expression: ^(?=.*[0-9]{3,})([a-zA-Z0-9_/+*.-]{6,})$ It works well when there are 3 consecutive digits, but not ...

Merge these two NPM packages together

Two npm projects exist: web-api (a library) and UI. The web-api utilizes gRPC-web to interact with the backend before converting it into a simple JavaScript object. In the UI, Vue.js is used in conjunction with web-api. Objective: merge these two project ...

What is the best way to customize the interval time for my specific situation?

I'm working on setting an interval in my app and I have the following code: HTML <div class="text"> {{currentItem.name}} </div> <ul> <li ng-repeat="item in items" ng-click="pickItem($index)">{{item.type}}</li> ...

Unlock TypeScript code suggestions for extended objects

In my app, I use a configuration file named conf.ts to consolidate config values from other files for better organization. By merging these values, it becomes more convenient to access them using Conf.MY_LONG_NAMED_VALUE rather than Conf.SubCategory.MY_LON ...

Problem with routing: Request parameters not being collected

I am currently working on a project to create a wikipedia clone. Initially, I set up an edit route that looks like this: router.get('/edit/:id', function(req, res){ var id = req.params.id; console.log(id); models.Page.findById(id, ...

Utilizing the power of d3.js within Angular 4

Currently, I have successfully implemented code to draw a polygon using the mouse in a normal JavaScript file. Now, I am looking to replicate the same functionality in my TypeScript file. Below is an excerpt from my d3.js file: //D3.JS VERSION 3 //------ ...

Issue - The module ./en.json could not be located when using the vue-i18n plugin

I recently integrated the i18n plugin into my existing Vue project to add localization. After following all the installation instructions from various sources (such as here), I made sure that each locale has its own file under /src/locales with the correct ...

From JSON to PNG in one simple step with Fabric.js

I am looking for a way to generate PNG thumbnails from saved stringified JSON data obtained from fabric.js. Currently, I store the JSON data in a database after saving it from the canvas. However, now I want to create a gallery of PNG thumbnails using thi ...

Output to the standard output stream after executing the `git clone` command

My goal is to execute the command git clone from within a Node.js program and have the output streamed to the standard output, just like it would be if run from a normal shell. However, I am facing an issue with using child_process.spawn as the output is n ...

Tips for designing an interactive walkthrough for a website with JavaScript

Some websites, such as Facebook games, incorporate step-by-step tutorials for new users using JavaScript to display pop-ups guiding the user on where to click next and explaining what is happening. How can one develop a similar system? What type of archit ...

Error in jQuery: the variable has not been defined

I am currently working on creating a custom plugin using the code below. I have encountered an error at the line if(options.controls == true) The specific error message says 'options is not defined'. How can I properly define this variable? ( ...

Is there a way for me to duplicate a complex element multiple times within the same page?

As an illustration, let's say I have a social tab located in my header that I would like to duplicate in the footer. This tab is comprised of various buttons with SVG images on top, event listeners linked to button IDs, and CSS styling. One option is ...