Is there a way to activate ng-class on only a single element?

In my code, I am using ng-repeat and ng-class for each element to select elements and add borders for the selected ones.

<div class="main-block_channel_create">
<section class="parent_messageList cancelDelete">
    <div id="section_animate" class="messagesList_block cancelDelete" infinite-scroll='messagelist.nextSet()' infinite-scroll-listen-for-event='anEvent' infinite-scroll-distance='100'>
        <!-- User Images List -->
        <a href="" class="messageBl message_preview animated" ng-repeat='preview in messagelist.previewList'>
            <div class="image_container_preview" ng-class="{community_select: item.isSelected}" ng-click='communitySelect(preview)' attr="{{preview.preview_id}}">
                <img class="deleteMessageBtn" src="images/close_icon.svg" ng-click="deleteMessage(preview.message_id)">
                <div class="spinner_container">
                    <!--<img src="/images/logo-80.svg" class='spinner_img'>-->
                    <img class="spinner_logo_vertical" src="images/logo_vertical-part.svg" alt="">
                    <img class="spinner_logo_left" src="images/logo_left-part.svg" alt="">
                    <img class="spinner_logo_right" src="images/logo_right-part.svg" alt="">
                </div>
                <img class="message_preview-image" src="{{preview.image}}" alt="">
                <!--  If no image is available, display text -->
                <div class="message_preview-text MediumNormalJunior" ng-if="!preview.image">
                    <div class="message_preview-text-inner" ng-if='preview.name'>
                        {{preview.name}}
                    </div>
                    <!-- Display 'empty' if there is no text either -->
                </div>
                <div class="empty_message" ng-if='!preview.text && !preview.image'>
                     <!--<h4>Empty</h4> -->
                </div>
            </div>
            <div class="stats" ng-show='preview.total_score > 0'>
                <p>{{preview.total_score}}</p>
            </div>
        </a>
        <footer class="listFooter">

        </footer>
    </div>
</section>

sass

.community_select
    border: 3px solid white

directive

(function(){
    'use strict';

angular
    .module('buzz')
    .directive('channelcreate', channelcreate);

function channelcreate($rootScope, $location, $timeout, $cookies, $window, communityApiService, getCommunities){

    return{
        restrict: "E",
        replace: true,
        scope: true,
        templateUrl: '/templates/channelCreate/channelCreate.html',
        link: function($scope){
            // $rootScope.showChannelCreate = null;

            // Select communities for create new channel
            $scope.communityList = [];
            $scope.communitySelect = function(communityId){
                $scope.selected = false;
                if ($scope.communityList.indexOf(communityId) == -1){
                    $scope.communityList.push(communityId);

                } else {
                    $scope.communityList.pop(communityId)
                }

                console.log($scope.communityList);
            };

            // all messages preview are loaded from messagesLoadFactory
            $scope.messagelist = new getCommunities();

        }
    };
};

})();

When clicking on a div, I can uniquely identify it using an id. How can I change only that specific element without affecting others?

Answer №1

When you log in, one option is to verify if the element's id is included in the selected elements list using

communityList.indexOf(preview.id) != -1
. This way, your ng-class will appear as follows:

ng-class="{community_select: communityList.indexOf(preview.id) != -1}"

Edit

Additionally, when removing an id from $scope.communityList, ensure that you locate its index first and then delete it using splice.

The section for adding/removing the id would now look like this:

// ... content omitted
$scope.communitySelect = function(communityId) {
  $scope.selected = false;
  var index = $scope.communityList.indexOf(communityId);
  if (index == -1) {
    $scope.communityList.push(communityId);
  } else {
    $scope.communityList.splice(index, 1)
    //                          ^^^    ^
    //        remove    starting_here  one_element
  }

  console.log($scope.communityList);
};
// ... content omitted

Answer №2

If you want to keep the selection on the screen highlighted, you can achieve this without maintaining an extra collection list. Simply add a flag called isSelected to each record and toggle it based on user click.

HTML

In my code, I utilize ng-repeat and ng-class for each element to select them (adding a border when selected).

<a href="" class="messageBl message_preview animated" 
  ng-repeat='preview in messagelist.previewList'>
    <div class="image_container_preview" 
     ng-class="{community_select: item.isSelected}" 
     ng-click='communitySelect(preview)' 
     attr="{{preview.preview_id}}">
</a>

Code

$scope.communitySelect = function(communityId) {
  item.isSelected = !item.isSelected;
};

To retrieve the list of selected previews, you can simply loop over the previews collection and identify those items with the isSelected flag checked.

var selected = $scope.previews.map(i => i.isSelected);

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

Error encountered while using JavaScript for waiting in Selenium

When using selenium and phantomjs to submit a form and then navigate back to the previous page, sometimes I encounter a timeout error as shown below: TimeoutError: Waiting for element to be located By(xpath,//div[@id='ContactFormBody']/div/br) W ...

Ways to design each element in React

I'm currently working on a React code that involves CSS for Scrolling functionality. When I try to use props.children.map, I encounter an error saying "TypeError: props.children.map is not a function". Since I am in the process of learning React.js, t ...

Disappearing Facebook share button: A common occurrence when navigating in Nuxt.js (Vue.js)

Within my nuxt.js web app, utilizing version 2.15.7, I have integrated a Facebook share button by following the instructions outlined in this comprehensive code example. Upon initial load of the application, the Facebook share button appears as expected. ...

Embedding images using a blob or base64 format does not function properly on iOS devices

I'm facing an issue with setting the src of an img tag to display an image. The code snippet below works fine on android, mac, and windows, but it is not functioning correctly on iOS: let base64Image = pageModel.image; this.$currentPageImage.src = `da ...

Store data in Firebase Storage and retrieve the link to include it in Realtime Database

Utilizing Firebase Realtime Database and Firebase Storage for this application involves uploading images from the pictures array to Firebase Storage. The goal is to obtain the Firebase Storage link for each image, add it to the object pushed into imagesU ...

"Enhance your website with autocomplete feature using the power of jQuery 1.4.2 and jQuery UI 1

Struggling to make jQuery autocomplete work. Despite searching for examples, most seem outdated. Modeled after a good example from the jQuery UI site but still can't get it to display data. My JSON data source is accessed via URL. [{ "pk": 1, "mo ...

Incorporating a feature to leave comments in JSON data through AngularJS

Yesterday, I completed an AngularJS test that presented me with two tasks. One task involved displaying the data of a JSON file on a webpage in HTML form. I accessed the FreshlyPressed JSON via the link "" and effectively showcased the thumbnail, pos ...

Integrating CSS with Material-UI in a React project: A step-by-step guide

I am currently developing a project using React (along with TypeScript) and the Material-UI library. One of my requirements is to implement an animated submit button, while replacing the default one provided by the library. After some research, I came acr ...

Utilizing onClick to target data within a .map function

I am struggling with the code provided below: const test = (e) => { console.log('example:', e.target.item.attributes.dataIWant); } {records.map((item, index) => { return ( <> <Accordion key={index} ...

Exploring the intricacies of React's useEffect: Solving the challenge of updating data when two separate dependency arrays are

I am facing an issue with two different useEffect hooks where the dependency arrays are different. const [dateFilterSort, setDateFilterSort] = useState({ queryText: initialQueryText(params.sortName), cardText: initialCardText(params.sortName), ...

Transmit form data via Ajax request

Thank you for your interest. I am looking to retrieve $_POST['Division'] from a dropdown list: <select name="Division" onchange="setImage2(this);"> <option value="1">Bronze</option> <option value="2">Silver</op ...

encountering an issue with server-side rendering of React causing an error

Node.js has been a bit of a challenge for me, especially when it comes to working with react and express. I have been struggling to find comprehensive tutorials and troubleshooting resources, leading me to ask minimal questions in the correct manner. While ...

Cryptocurrency price tracker with sleek Bitcoin symbol and FontAwesome icons

My assignment involved creating a function that retrieves Bitcoin trades from a JSON URL, allows users to change the interval with buttons, uses fontawesome arrows to indicate rate changes (up/down/no change), and displays the data on a website. Everythin ...

Bringing in PeerJs to the NextJs framework

Currently delving into NextJs and working on creating an audio chat application, I've hit a roadblock while attempting to import PeerJs. An error message keeps popping up saying 'window is not defined'. import Peer from 'peerjs'; ...

Updating Select Options Disabled/Enabled in Angular 2

In my Angular2 project, I have 2 select elements: <div ng-controller="ExampleController"> <form name="myForm"> <label for="companySelect"> Company: </label> <select name="companySelect" id= ...

Refine objects based on their properties without removing them from the dataset

I have a specific object structured as follows: var myObj: { 2:"None", 20:"A", 31:"A", 32:"A", Social:"B", Method:"None" } My goal is to retrieve the object without the properties 'Social' and 'Method'. Initia ...

What could be causing the issue with npm install packages not functioning properly?

Currently, I am in the process of setting up and deploying a particular git repository locally: https://github.com/maxie112/gatsby-ecommerce-theme I am strictly adhering to the instructions provided for Mac OS. Here are the encountered error logs; maxden ...

Are NPM and Eslint supposed to be this confusing, or am I missing something?

Recently, I've started delving into the world of JS and have been eager to learn more about linting. Following a tutorial, we set up the lint stage in our package.json file. The configuration looks like this: "lint": "./node_modules/.bin/eslint ." U ...

What is the process to assign a value received from the server to an Input field and then update

I am working on an input field that should initially display a value from the server const [nameValue, setNameValue] = useState(""); <TextField id="outlined-read-only-input" label="Display Nam ...

Implementing closure within a recursive function allows for better control

One of my functions is designed to take a parameter and print the last number in the Fibonacci Series. For example, if the parameter is 3, it would return 2 as the series progresses like 1, 1, 2. function recursionFib(num){ if(num ...