Manipulate a pair of span elements with a singular function in AngularJS

I have a pair of span tags and p tags as follows:

<span class="span1" ng-click="show()">Span_1</span>
<p class="p1" ng-show="var1">P_1</p>
<span class="span2" ng-click="show()">Span_2</span>
<p class="p2" ng-show="var1">P_2</p>

Using AngularJS, my goal is to create a single function like "show()" above that toggles both p tags. How can I achieve this? Here's the corresponding JavaScript code:

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.var1 = false;
    $scope.show = function() {
        $scope.var1 = $scope.var1 === false ? true: false;
    };
});

When I click on Span_1, only the corresponding p tag should show, same for Span_2. This functionality should be achieved using just one function.

Check out the Plunker example here: http://plnkr.co/edit/fzgpV68Q7UnHGHmHffZZ?p=preview

Answer №1

Passing variables from HTML and implementing conditional logic using AngularJS.

//Angular code(js)

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
  $scope.variableList = [{state:true},{state:false}];
    $scope.show = function(what,where) {
        switch(what){
          case 'display':
            return $scope.variableList[where].state;
            break;
          case 'click':
            $scope.variableList[where].state = !$scope.variableList[where].state;
            break;
          case 'class':
            return ($scope.variableList[where].state ? 'active' : '');
            break;
        }
    };
});

Usage(HTML):

<div ng-app="myApp" ng-controller="myCtrl">
  <div ng-repeat="item in variableList">
    <span ng-class="show('class',$index);" ng-click="show('click',$index)">Span_{{$index+1}}</span>
    <p ng-class="show('class',$index);" ng-show="show('display',$index)">P_{{$index+1}}</p>
  </div>
</div>

Answer №2

If you want to create a toggle method that can switch the visibility of a specific element, you can use the following example code:

<html ng-app='myApp' >
  <body ng-controller="myCtrl">
<span class="span1" ng-click="toggle()">Span_1</span>
<p class="p1" ng-show="var">P_1</p>
<span class="span2" ng-click="toggle()">Span_2</span>
<p class="p2" ng-show="!var">P_2</p>
    </body>
  </html>

Here is the JavaScript code for this functionality:

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.var = true;
    $scope.toggle = function() {
        $scope.var = !$scope.var;
    };
}); 

Answer №3

To modify the value of either $scope.var1 or $scope.var2, you can pass a specific span number as a parameter to a function. The function will then toggle the value based on the parameter provided:

function updateValue(varParam) { 
    if (varParam === 1) {
        $scope.var1 = !$scope.var1; //toggle value    
    } else {
        $scope.var2 = !$scope.var2;
    }
}

In your template, you would call the function and pass the parameter like this:

ng-click="updateValue(1)"

Check out this Working Plunkr for a demonstration.

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

Importing JavaScript into an Angular component: A beginner's guide

Within my Angular-11 project, I have included the following JavaScript file: "node_modules/admin-lte/plugins/bs-stepper/js/bs-stepper.min.js", I have added it to the angular.json configuration as detailed above. import Stepper from '.. ...

Ways to align div elements

I am currently in the process of developing my own custom animation player. Utilizing Three.js for object rendering has been successful so far. However, the challenge lies in incorporating control options at the bottom of the player interface (such as play ...

Guide to making type-safe web service requests using Typescript

When utilizing Angular for web service calls, it's important to note that the type of the returned object is not automatically verified. For example, let's say I have a Typescript class named Course: export class Course { constructor( publ ...

What is the best way to sum up array elements until they equal a target number, and then create objects using these summed values?

Suppose I have an array containing 5 different values for width, with a maximum width of 6 that needs to be reached. How can I iterate through the array and construct an object with those values each time it hits the maximum value without exceeding it? Le ...

Using Angular JS to send and receive JSON data with Django Rest Framework comment form

Initially, I utilized the following ajax call to transmit the POST data to the django rest framework API. $('#comment_form').on('submit', function(e) { e.preventDefault() $.ajax({ type:"POST", url: '/api/comments/create ...

Guidelines for implementing a database update post drag and drop action with JavaScript and AJAX?

Providing some context, I have set up three divs for dragging and dropping items. The first div acts as the default starting point, while the second and third divs are meant to update the database when content is dropped into them. These divs will be dynam ...

Mobile phone carousel glitch

I am encountering an issue with the Bootstrap v4.0 Carousel that I can't seem to resolve. Despite searching online for similar problems, I have not been able to find a solution, which is quite perplexing. Whenever I load a page on an iPhone, the caro ...

When the Promise object is assigned to the img [src], the image may occasionally be set to null

I incorporate Angular into my Electron application. One of the components in my app contains an array called files, where each element is an object with a member named preview. This preview member is a Promise object that returns a file:// object. <mat- ...

Issue with the dropdown functionality in an Angular reactive form

I am experiencing an issue with a select dropdown in my Angular project. I have implemented a reactive form, but the dropdown is not functioning as expected and I am unsure of how to resolve this issue. Could someone offer assistance or guidance on how to ...

Incorporating SEO for a Flash-Based Website

After reading through various discussions on this topic, it seems like my question still remains unanswered. We are gearing up to revamp our company's website in the coming months. Currently, our site is mostly text-based, which has helped us achieve ...

Issues with Express routes - encountered POST 404 (Not Found) error

I'm having trouble with my routing setup in login.js for login.component.js. It seems that when I try to use routes specified within login.js, such as axios.post('http://localhost:5000/login/add3', user), it's not connecting properly. H ...

Utilizing blueimp to upload an image and implementing a function structure that shares similarities

This is the outline of my structure: <html> <head> <title></title> <meta charset="utf-8"> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <script src="vend ...

Tips for handling alternate lines with two distinct styles in the Ace editor

I am looking to develop a unique note-taking editor using Ace. For instance, if I paste some Spanish text into the editor, I would like to add English words as notes for corresponding Spanish words. My goal is to display these English words above the resp ...

Menu Styled <ul> Not Activating handlerOut

My navigation menu is structured using an unordered list (<ul>) with customized styling (see markup & CSS below) <ul id="TopNavigation"> <li><a href="#" id="products" class="products">PRODUCTS</a></li> ...

Angular 2 is throwing an error, stating that Observable is not defined

I'm currently working with Observable and ChangeDetectionStrategy to notify other components about any changes that occur. However, I am encountering an issue where the Observable object addItemStream is coming up as undefined. Can anyone spot what mi ...

Angular not displaying input value correctly in first loop index

Hello, I am currently working on a rent calculator application using Angular. The app takes three inputs: total rent, annual rent increase amount, and the number of years to calculate for. One issue I am facing is that the for loop does not print the enter ...

Can you share any recommendations or instances of modifying data within HTML tables using Laravel?

Has anyone ever needed to directly edit and update data in a HTML table using Laravel? I have successfully created "create" tables for different tasks, but I'm interested in being able to modify the data directly on an "index" page. While there are ...

Every initial test with Protractor ends in failure

Here are the versions I am currently using: protractor v5.1.2 chromedriver v2.33 node v6.11.4 npm 3.10.10 selenium-webdriver v3.0.1 I am a beginner with protractor and I am attempting to run the provided test natively included in protractor. The test scr ...

What techniques can I use in Angular to access and modify properties like validity in nested child scopes?

I created a basic form with the following structure: <form name="myForm"> <input name="field" ng-model="item.field"></input> <button ng-click="save()">Save</button> </form> In theory, I should be able to modify fie ...

Verify if the link includes https:// while using angularjs

In my angular app, there is a lot of data stored in JSON format. [ {"link": "https://stackoverflow.com"}, {"link": "https://stackoverflow.com"}, {"link": "id-aW783D"}, //This data is incorrect {"link": "https://stackoverflow.com"} ] However, the ...