The ng-class directive isn't functioning as anticipated when paired with ng-repeat

Here is the HTML code I have:

<div ng-click="changeBorder(value)" ng-class="{active_borders:isActive(value)}" ng-repeat="value in values">
            <img class="card-img-bottom" src="{{value.Imagen}}" />
        </div>

This is my Javascript code:

$scope.isActive = function isActive(value){return $scope.valueSelected.Id==value.Id;}

$scope.changeValue=function changeValue(value){$scope.valueSelected=value;}

EXPLANATION: I am trying to achieve a functionality where clicking on a div, containing an image, will change the border color of that specific div. Only the last clicked div should have its border colored.

MY PROBLEM: The issue I am facing is that the isActive() function is being executed twice instead of once during the ng-repeat cycle as intended.

I want to avoid this double execution because the function involves database communication, and it could cause complications if it runs constantly.

Answer №1

One possible explanation for the double evaluation of isActive is that Angular evaluates all bindings on a page during the digest cycle to ensure synchronization with model data. This behavior is typical in AngularJS applications and does not significantly impact performance, especially when it involves an equality check like

$scope.valueSelected.Id==value.Id;
.

The frequency of execution for the isActive function can vary depending on the application's requirements.

If you have concerns about the function running multiple times due to additional tasks such as database communication, it is best to avoid including API calls or network operations within binding functions. This can lead to continuous executions and instability in the digest cycle.

It is recommended to handle database calls within a separate method like $scope.changeValue which should only be triggered by user actions. This approach aligns with good architectural practices and ensures that the application functions as intended.

Answer №2

Angular reiterates functions within scope multiple times to accommodate dependencies that may have a ripple effect on other variables. If this repetitive behavior becomes problematic, it might be time to explore alternative strategies since halting the process is not an option. The task of IsActive should be singular: confirming whether an object is active without initiating API requests. Take a step back and revisit your controller's design to minimize redundant calls.

UPDATE: To clarify, there are instances where you can prevent duplicate calls. However, relying solely on one call is risky, and incorporating API requests in what essentially should act as a "GET (a read method)" is not the recommended approach.

Answer №3

Give this a shot! Just remember to set the default value of $scope.valueSelected = {} unless you want it to throw an error saying it can't read property id of undefined.

<div ng-click="changeBorder(value)" ng-class="{'active_borders':valueSelected.Id==value.Id}" ng-repeat="value in values">
    <img class="card-img-bottom" src="{{value.Imagen}}" />
</div>

Answer №4

Perhaps you might find this helpful. Try using the code snippet below with id="{{value.id}}"

<div id="{{value.id}}" ng-click="changeBorder(value)" ng-class="{active_borders:isActive(value)}" ng-repeat="value in values">
            <img class="card-img-bottom" src="{{value.Imagen}}" />
        </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

Is it possible to incorporate Vue and Vuetify into an existing project that requires IE compatibility?

Currently in the process of enhancing a legacy project with new functionality. The front end is currently relying solely on jQuery for all the webpages. I have been tasked with adding another webpage and would like to incorporate Vuetify + Vue due to the i ...

Avoiding Overlapping in Recharts Scatter Plot

I am encountering an issue where the data I'm inputting into recharts is not overlapping, instead it is being stacked horizontally. This "stacked" data all has the same date on the x-axis and the same count on the y-axis. What I actually want is for t ...

Is there a way to display the number of active users currently on a page using Pusher?

My goal is to create online classrooms with a maximum of two people in each room, allowing the teacher to know when both the teacher and student are connected. I attempted to track the number of users connected using Pusher's members.me function but ...

Visual Studio Code unable to locate source maps for typescript debugging

Looking for some help debugging a basic Hello World TypeScript file. Whenever I try to set a breakpoint, it seems like VS Code is having trouble locating the source map, even though it's saved in the same directory. I'm using Chrome as my browser ...

When closing the menu in Bootstrap, the page automatically scrolls back to the top

Whenever I open my menu, click on a link, and scroll down the page using the menu, upon closing the menu I am automatically taken back to the top of the page. I have experimented with the following scripts: let y = window.scrollY; let offcanvas = docume ...

Having trouble with res.redirect not working after the page has been rendered with data?

I have a basic forget password feature set up, where users can request a password change and receive an email with a token. Clicking the link in the email will redirect them to a page where they can input their new password. When I click on the email link ...

There seems to be a problem with the Bootstrap Container and Container Fluid

I am currently utilizing Bootstrap 3.3.7 and have incorporated buttons to enhance the content on my webpage. Upon using container-fluid, I noticed that it does not expand the content across the entire page but rather confines it to the center area of the ...

Here's a unique version: "Discovering how clients can easily connect to a new room using socketio

There are 5 rooms on my server named "A", "B", "C", "D", and "E." Server-Side In the server side code: io.on('connection', (socket) => { console.log('New user connected'); socket.on('disconnect', () => { ...

Unable to retrieve value from a hidden input field using JavaScript

My goal is to retrieve a value from a hidden inputbox using JavaScript. However, I am encountering issues where sometimes I receive an "undefined" error and other times there is no output at all. When I utilize alert(document.getElementById('hhh& ...

Reordering sections in a dynamic manner

I'm working on a single-page website with four sections arranged like this: <section id=“4”> <section id=“3”> <section id=“2”> <section id=“1”> Now, I want to change the order of these sections when scrolling ...

What is the process of using AJAX, JavaScript, and HTML to submit data to a remote

I need help with sending data from an HTML page to a server. I have a JSON example below that illustrates what I want to achieve. On my HTML page, I have a question label and four options (A, B, C, D) as radio buttons. After clicking the send button, I ...

What is the reason for jQuery selector variables not functioning within namespaces?

I'm struggling to figure out why my code isn't working as intended. I'm trying to declare multiple variables, but something seems to be off. Can anyone help me spot the mistake? var message = (function ($) { var $modalBody = $( ...

Guide for adding Chinese characters with digital signature in your jsrsasign.js code

I am currently working on integrating with third-party organizations that require a digital signature to be added to the data in the request header. After some research, I decided to utilize the jsrsasign.js library for handling the digital signature proc ...

Steps to eliminate the select all checkbox from mui data grid header

Is there a way to remove the Select All checkbox that appears at the top of the checkbox data column in my table? checkboxSelection The checkboxSelection feature adds checkboxes for every row, including the Select All checkbox in the header. How can I ...

Guide on Importing All Functions from a Custom Javascript File

As a beginner in learning Angular, I am faced with the task of converting a template into Angular. However, I am struggling to find a solution for importing all functions from a custom js file into my .component.ts file at once. I have already attempted t ...

Retrieve the data attribute of the "root" element within the React.js DOM

Imagine there is a <div> element within an HTML file: I am looking to transfer the attribute data-person-name from that particular <div>, which has the ID of root, to a React element. <div id="root" data-person-name="John"></div> ...

Having trouble using the `.not` function in jQuery

I'm working on implementing a collapsible menu using jQuery. When any header is clicked, the next sibling (the box) should expand while all other boxes collapse. HTML <div class="finbox" id="finbox1"> <div class="finheader" id="finheade ...

How can I transfer data from an API response containing an array of objects to a new array in a Vue.js

How come I am getting NaN instead of "qwe" and "qweqweqwe" when trying to push the first 6 elements from an array of objects to a new array? Imagine the array of objects retrieved from the API is structured like this: 0: {id: 340, name: "qwe", lastname: ...

Using JavaScript, create a script that will automatically convert the value of an AJAX calendar to a datetime

I am struggling with converting a string into a proper date format using JavaScript in an ASP.net textbox with AJAX calendar extender control. <asp:TextBox ID="tbxReceivedDate" CssClass="selectstyle" runat="server" MaxLength="100" Width="200" onblur="p ...

Ways to focus on a specific div using JavaScript

I am attempting to create a 'snow' effect on the background of a particular div with a red border. Here is the code, but you can also view it here: <!-- language: lang-js --> var width = getWidth(); var height = getH ...