Apply the "ng-class" attribute to the parent of the chosen element

Another question arises in relation to the usage of ng-class...

How can we dynamically add a class to the <ul> element when a <button> within its <li> is clicked?

Check out the demo here

Here is the HTML code snippet:

<div ng-app="myApp">
<section ng-controller="myCtrl">
    <ul>
        <li ng-repeat="item in model.items" class="commonClass">{{ item.name }}</li>
        <li><button>
        active
        </button></li>
    </ul>
    <ul>
        <li ng-repeat="item in model.items" class="commonClass">{{ item.name }}</li>
        <li><button>
        active
        </button></li>
    </ul>
</section>
</div>

And here is the corresponding JavaScript code:

var app = angular.module('myApp', []);

app.controller('myCtrl', function ($scope) {

    $scope.model = {
        selected: null,
        items : [
            {name: "Apple"}, 
            {name: "Banana"}, 
            {name: "California"}
         ]
    };
})

Answer №1

Give this a shot

var application = angular.module('myApp', []);

app.controller('myCtrl', function($scope) {

  $scope.scenes = [{model: { selected: null, items: [{ name: "Apple" }, { name: "Banana" }, { name: "California" }] }}, {model:{ selected: null, items: [{ name: "Apple" }, { name: "Banana" }, { name: "California" }] }}];

  /* $scope.model = {
    selected: null,
    items: [{
      name: "Apple"
    }, {
      name: "Banana"
    }, {
      name: "California"
    }]
  }; */
})
.on {
  color: red
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="myApp">
  <section ng-controller="myCtrl">
    <ul ng-class="{'on': ul.onIsOn}" ng-repeat="ul in scenes">
      <li ng-repeat="item in ul.model.items" class="commonClass">{{ item.name }}</li>
      <li>
        <button ng-click="ul.onIsOn = !ul.onIsOn">
          active
        </button>
      </li>
    </ul>
  </section>
</div>

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

Ways to verify if Angular has been properly loaded

Imagine if I want to use angularjs from a CDN, but also have a backup in case the CDN request fails - perhaps by pointing to a local js file. For JQuery, there are examples of using javascript like this: if(typeof jQuery == 'undefined') { .. ...

Exploring React-Query's Search Feature

Looking for guidance on optimizing my Product search implementation using react-query. The current solution is functional but could be streamlined. Any suggestions on simplifying this with react-query would be greatly appreciated. import { useEffect, use ...

Make the minimum height of one div equal to the height of another div

My query is somewhat similar to this discussion: Implementing a dynamic min-height on a div using JavaScript but with a slight twist. I am working on a dropdown menu within a WordPress site, integrated with RoyalSlider. The height of the slider div adjust ...

Finding multiple locations with Google Maps API Geocoding

I've created a small JavaScript code to geocode various locations and display them on a map. While I can successfully plot a single location, I'm struggling to get it working for multiple locations. Below is the code that currently works for one ...

Is there a jQuery tool that can effortlessly add items to a list element?

I'm currently developing a task management application on the web. I have a textarea where users can input tasks, and when they press enter, it should automatically be added to a list element (li). The adding functionality works, but only after refres ...

The getServerSideProps function in Next.js is only executed once, meaning it won't retrieve fresh data when accessed via next/router

I'm working on a Next.js application with Server-Side Rendering (SSR) where I have an async function called getServerSideProps that is exported like this: export const getServerSideProps = getGenericServerSideProps([""]); The getGenericServerSideProp ...

Issue with dynamic form JavaScript functionality after removing curly braces { } from a select tag in Rails

In my Rails form, there is a gender field defined as follows: <%= f.select :gender, ["Male","Female"],{class: "gender"} %> I also tried adding an onclick event like this: <%= f.select :gender, ["Male","Female"],{class: "gender"},onclick: "categ ...

Save updated tags only when the form is submitted in ngTagsInput

Can the sending of a new tag to the server be disabled after adding it to the input and saving it later by clicking a submit button? This is my Controller: vm.tags = []; $scope.loadTags = function (query) { return $http.get('api/tags?query=' ...

I'm trying to retrieve information from openweathermap in order to show it on my app, but I keep running into an error that says "Uncaught RangeError: Maximum

I recently created a div with the id 'temporary' in order to display data retrieved from the openweathermap.org API. However, I am encountering an error in the console and I'm not sure why. This is my first time working with APIs and I would ...

Troubleshooting the malfunctioning of the Bootstrap slide animation

I've been attempting to implement scroll animation on a div, but for some reason, it's not working as intended. I must have made a mistake somewhere, but I can't figure out where. Any help in resolving this issue would be greatly appreciated ...

There is a method in TypeScript called "Mapping IDs to Object Properties"

I'm currently developing a React app that features several input fields, each with its own unique id: interface IFormInput { name: string; surname: string; address: string; born: Date; etc.. } const [input, setInput] = useState< ...

What is the method for retrieving a value using the Angular forEach function?

I'm encountering an issue with retrieving values from an angular forEach loop. Below is the data I am working with: vm.memberDetails={ "member": [ { "firstName": "HARRY UTTWO", "lastName": "POTTER", } ...

"Struggling with a basic Javascript function to refresh parts of a web page by calling a .php

After spending several hours browsing the internet, I am still struggling to get this straightforward example to function properly. Could someone please lend me a hand? My goal is to use JavaScript to display the contents of a PHP file. The display should ...

Tracking the latency of WebSockets communications

We are in the process of developing a web application that is highly responsive to latency and utilizes websockets (or a Flash fallback) for message transmission to the server. While there is a fantastic tool known as Yahoo Boomerang for measuring bandwidt ...

Delete the final element from the json object

I need to extract the data from a JSON object and exclude the last element called 'week2'. Here is the object with properties like username, Geo, status, month, and week2: const response = [{ Username: "Denisse Morales", Geo: "NSU", ...

Issue with hook not updating when invoked inside useEffect

I'm encountering an issue with updating the state after fetching data from my API. The API response seems to be correct, but for some reason, my weatherData-hook is not getting updated and it returns undefined. Can anyone point out what mistake I migh ...

Develop a vector and embed it automatically in PHP

I am working on a program that automatically creates vectors based on client input in a function. The function retrieves data from the client, and if the client specifies they are from Tirana City, the function will generate a stack to store and manipula ...

Error: Attempting to modify the 'chat_room_id' property of an undefined object results in a TypeError when ng-if is used

Currently facing a roadblock in my project. I am developing a chat feature that is located within a Rails partial in the application.html.erb file. The goal is to have a user's list of friends displayed in the chat area initially. When a user clicks ...

Guide on retrieving information from Spark and showcasing it through Angular

Trying to navigate the world of Spark framework and AngularJS as a beginner, I set out to create a basic REST application. However, I hit a roadblock when it came to retrieving data from the server and displaying it using Angular. My initial task was simp ...

What is the best way to pass a value back to the main function from an async.eachOfSeries function?

Currently, I am utilizing the async npm library in my project. I am interested in finding a way to return the value of 'someVar' back to the main function. The documentation indicates that it returns a promise if a callback is not provided. Howe ...