Exploring the ng-repeat directive's scope

Each item on my list can be highlighted when clicked, using the selectedData class.

<div>Remove highlight </div>
<ul>
 <li ng-repeat="data in inputData">
    <span title="{{data}}" ng-class="selected ? 'selectedData' :  ''" ng-click="selected = !selected;">
        {{data}} 
      </span>
  </li>
</ul>

I am looking to clear all highlights from the list items (and therefore remove the selectedData class) when a clear button outside the list is clicked. In other words, I need to reset selected for each <li>. Since ng-repeat creates its own scope, what is the best way to achieve this?

Answer №1

Give this a try:

<ul id="myList"... ng-repeat...>
  <div ng-class="active: isActive[$index] ? 'activeItem' : ''" ng-click="isActive[$index] = !isActive[$index]">

</ul>

function reset() {  

  for (i = 0; i < isActive.length; i++) { 
    isActive[i] = false;
  }
}

Answer №2

@Sidharth Panwar's response seems mostly accurate

However, I have some doubts regarding the necessity of selected: in

<span ng-class="selected: selected[$index] ? 'selectedData' : ''"
. I was able to get it to work using only the ternary operator:
// Insert code here

angular.module("app",[])
.controller("controller", function($scope){
  $scope.selected=[]; // <--- crucial part of the solution
  $scope.clearSelector = function(){
    for(var i = 0; i < $scope.selected.length; i++){
      $scope.selected[i] = false;
    }
  };
});
.highlight{
  color:red;
}
<!DOCTYPE html>
<html ng-app="app">

  <head>
    <script data-require="angular.js@*" data-semver="1.5.0" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular.js"></script>
  </head>

  <body ng-controller="controller">
    <ul ng-init="temp=[1,2,3]">
      <li ng-repeat="i in temp" ng-click="selected[$index] = !selected[$index]" ng-class="selected[$index]?'highlight':''">
        toggle between black and red
      </li>
    </ul>
    <button ng-click="clearSelector()">clear</button>
  </body>

</html>

If you are worried about ng-repeat having its own scope and being unable to manipulate its values from the parent scope (where the "clear" button is located), creating an array in the parent scope can help centralize control variables:

// both in child scope
selected=1;    // create a new variable if no existing variable named
               //"selected" exists in the current scope,
               // this occurs when JavaScript knows how to create primitives
selected[0]=1; // need to determine the address of "selected". If not found
               // in the current scope, search in the parent scope

For more detailed information, refer to this link on inheritance and scope

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

What is the best way to add query parameters to router.push without cluttering the URL?

In my current project, I am using NextJS 13 with TypeScript but not utilizing the app router. I am facing an issue while trying to pass data over router.push to a dynamically routed page in Next.js without compromising the clarity of the URL. router.push({ ...

Headers cannot be set once they have already been sent in an express js application

After reviewing various responses to this query, I am baffled as to why this error keeps appearing despite having res.send() in multiple paths. In my code (expressjs 4.13), it looks something like this: var user ={ username: "some", password: "a" ...

In a carousel slider, the height and width of divs are not set to specific dimensions

For a code snippet, you can visit this link: here The html: <html lang="en"> <head> <link href="https://fonts.googleapis.com/css?family=Lato:400,400i,700,700i|Merriweather:300,400,700" rel="stylesheet"> <link href="https://ma ...

The provider for authentication, which is linked to the AuthenticationService and subsequently to the loginControl, is currently unidentified

Attempting to implement an authentication service in my application, I encountered an error when trying to call it within my controller: !JavaScript ERROR: [$injector:unpr] Unknown provider: AuthenticationServiceProvider <- AuthenticationService <- ...

Create a custom element in React to detect and encapsulate links

I could really use some assistance with this issue. I have a bunch of text blocks containing links and have been utilizing linkifyjs's React component to automatically wrap the links in anchor tags. However, now I am looking to add a custom button nex ...

Iterate through Javascript quotes and automatically navigate to the first quote once the loop is completed

I've encountered an issue with the script where I am unable to loop back to the first element once all child elements have been traversed. https://jsfiddle.net/pad5bp0o/2/ Here is the jQuery code snippet: $(document).ready(function() { var length ...

Implement a React Component as a unique OverlayView within the Google Maps application

Utilizing the Google Maps JavaScript API V3, I have created a map with clustered and draggable map markers. Instead of relying on React libraries that interact with the google maps API, we chose to build our own solution due to limitations in drag function ...

Capture an entire webpage screenshot with Webdrivercss

When trying to capture a screenshot of an entire webpage, I encountered a challenge. The code I used below with Firefox successfully took a screenshot of the whole page, but it didn't work with Chrome. According to the API documentation, I should use ...

Validating user input fields to display error messages when empty

As part of my program, I need to gather information from users regarding their name and the number of pets they have. If a user enters an empty string, I want to display an error message prompting them to input something and fill the text box with their en ...

Troubleshooting jQuery compatibility issue in IE6 when using javascript and loading content through ajax

Encountering issues with IE6 and javascript applied to ajax content. Unable to use any type of javascript (plain or with jQuery) on the ajax-retrieved content. The main html page loads the Header content using ajax (specifically utilizing the jQuery ...

Dropdown menu featuring a customizable input field

Is it possible to have a drop-down list with an input textbox field for creating new items in the same dropdown menu? ...

Display modal popup only once the dropdown has been validated, with the validation focusing on criteria other than the dropdown itself

Looking for a way to validate dropdown values. Popup should only show if the dropdown values are selected; otherwise, the popup should remain hidden. Below is the code snippet: <div class="main-search-input-item location"> ...

Stuck with the same icon even after a successful AJAX call

I am currently working on implementing a 'add to my list' function in my web app. The goal is to change the color of an icon when a user clicks on it, after sending the necessary data to the server. Despite successfully sending the data to the s ...

Learn the process of establishing a connection to a remote MongoDB server from an Angular-Spring application running on a separate server

My MongoDB is currently hosted on X box, while the Angular-Spring Application is hosted on Y box. When both are running locally, my application functions properly; however, upon configuring them at the server level, I encountered the following issue: HTTP ...

Struggling to render multiple images using Gatsby + GraphQL with `{data.allFile.edges.map(({ node })}`

Description I'm attempting to utilize {data.allFile.edges.map(({ node }) to display multiple local images on a page, but I'm encountering errors when trying to run gatsby develop. Steps to replicate Below is the code I am using: import React fr ...

Error encountered in Three JS Drag Controls: Unable to assign value to property 'x' as it is undefined

I've been trying to drag the spheres around the scene using drag controls that should be activated when the "m" key is pressed. However, I keep running into an issue where the objects don't move and I receive an error message saying "Uncaught Typ ...

Trouble with jquery/ajax form submission functionality

I followed a jQuery code for form submission that I found on various tutorial websites, but unfortunately, the ajax functionality doesn't seem to be working. When I try to submit the form, nothing happens at all. I've tried troubleshooting in eve ...

To dismiss the Div, simply click on any area outside of it. Leveraging the power of SVG, D3

I need a way to hide my div by clicking outside of it. My SVG has a background and a graph with nodes on top of that. I have a special node (circle) on the graph, clicking on which makes a box appear. To show the box, I use the following code: d3.select ...

Exploring a JavaScript multi-dimensional array

Hello everyone, I need assistance with manipulating this array: [[2,3,0],[0,4,5]] I am looking to rearrange this array as follows: [[2,0], [3,4], [0,5]] Does anyone have any suggestions on how to achieve this? I am using JavaScript for this project. ...

Puppeteer headful Browser running on Node JS fails to start

Experimenting with puppeteer to explore browser automation techniques. I'm trying to launch the chromium browser in visible mode rather than headless, so I've set the launch option to false. However, Chromium still isn't opening as expected. ...