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

Revamp the design of the Google image layout

I am trying to replicate the layout of a Google search results page. My goal is to have a full-width div appear on screen when an image is clicked, with a small triangle at the bottom of the clicked image. I attempted to place the img inside another div, ...

Is it necessary for JavaScript functions to be stored in a separate file in order to be invoked?

Here is the scenario that unfolded: Within a .php file, I had the following form: <form action="/flash_card/scripts/create_user_gate.php" onsubmit="return validateForm()" method="post"> <table align="center"> ...

What is the best way to receive a callback when a user cancels a dialog box to choose a mobile app after clicking on

I am currently exploring HTML coding for mobile devices and looking to integrate map routing functionality. When it comes to mobile devices, utilizing the local app is the more practical option, and I have had success implementing this by modifying the l ...

How can Selenium interact with various shadow DOM elements within a dropdown menu?

I am attempting to interact with a dropdown menu in order to track activity on the page when clicking on one of its items. Here is an overview of my HTML structure: <slot> #shadowroot <myoption-cmp> #shadowroot <some anchor te ...

What is the best way to retrieve the value stored in a variable?

In my Node.js program, I have a snippet of code where I am working with a map named `transMap`. My goal is to retrieve the value for 'yy', which should be "ipaddress", and then output it as JSON. While I expected the JSON response to be { "ipaddr ...

Finding the Attachment ID on a JIRA Issue Page with JavaScript

Currently, I am using an ajax call that requires the attachment id in its URL. The URL is hardcoded as follows: url: AJS.contextPath()+"/rest/api/latest/attachment/10415" jQuery.ajax({ url: AJS.contextPath()+"/rest/api/latest/attachment/10415", TYPE: "GET ...

The output of new Date() varies between app.js and ejs

app.get("/test",function(req,res){ var d = new Date(); res.send(d); }); When I access mydomain/test, it displays the output "2019-03-19T04:50:47.710Z" which is in UTC. app.get("/testejs",function(req,res){ res.render("testejs");}); Below is the content ...

Jquery's intermittent firing of .ajax within if statement

So, I've inherited a rather messy codebase that I need to modernize. The task involves upgrading from an old version of prototype to the latest jQuery 3.2.1 within a dated website built on php and smarty templates (not exactly my favorite). When a lo ...

HTML/JS Implementation: Back to Top Visual Element

- This website appears to be quite simple at first glance. However, I have encountered an issue where every time I scroll down and then click on the "About" menu option, it abruptly takes me back to the top of the page before displaying the section with a ...

Struggling to fill in fields using express and Mongodb

I am facing an issue with populating the fields of two models, Post and User. const PostSchema = new Schema({ text: { type: String }, author: { type: mongoose.Schema.Types.ObjectId, ref: 'user' } }) cons ...

Error encountered: Mocha - The property '$scope' cannot be read as it is undefined

I encountered an issue: Error: Type Error - Cannot read property '$scope' of undefined at $controller (angular/angular.js:10327:28) at angular-mocks/angular-mocks.js:2221:12 at Context. (src/client/app/peer-review/post-visit.co ...

What's the process for including delivery charges in Stripe transactions?

I am facing an issue with Stripe where I am unable to incorporate delivery fees into my transactions. How can I successfully integrate this feature? let line_items = []; for (let productId of uniqIds) { const quantity = productsIds.filter(id => id == ...

Create an Oval-Shaped Image Cutout

Currently, I have a fabric.JS canvas where objects can be added. However, I am interested in clipping these objects into an oval shape, similar to the clip demos on fabricjs.com. In my current project (JSFiddle), I have been able to crop the object into a ...

What steps do I need to take to modify the text in the ionic navbar

Here is a snippet of my code... <ion-side-menu-content> <ion-nav-bar class="bar-stable"> <ion-nav-back-button> </ion-nav-back-button> <ion-nav-buttons side="left"> <button class="button b ...

Suggestions for deleting browser cache programmatically by utilizing JS or HTML

Having trouble clearing the Chrome browser cache using Add-ons. Working on a site development project using JSP with Java, it's crucial for security reasons to clear the cache. Tried multiple methods but none have been successful. Any suggestions? Ple ...

The toggle feature doesn't seem to be working properly in Bootstrap 5

I've tested it in the latest Bootstrap version and still can't get it to work. I even switched to version 5, but the toggle functionality remains a problem. I've tried various solutions from StackOverflow with no luck ** I've added all ...

Creating an executable JAR for your Next.js application: A step-by-step guide

Is there a way to ensure that my Next.js file can run seamlessly on any computer without the need for reinstallation of all modules? In my folder, nextjs-node, I have the following subfolders: components lib public node_modules page style package.json I ...

Which specific values could cause the function to fail?

I am considering implementing the function provided below: function removeDuplicates(array){ var output=[],object={}; for(var index=0,length=array.length;index<length;index++){ object[array[index]]=0; } for(index in object){ ...

Merging Vue props with v-for for powerful data handling

Below is an example of my child component HTML: <div v-for="(input, index) in form.inputs" :key="index"> <div> <input :name"input.name" :type="input.type" /> </div> </div> JavaScript (Vue): <script> export d ...

Building a Dynamic CSS Grid

Today is the first time I'm reaching out for help rather than figuring things out on my own. I'm currently working on a website layout that consists of visible tiles all with equal sizes, forming a grid structure. The challenge I face is making t ...