Apply a specific style conditionally using Angular's ng-repeat directive

Currently, I am utilizing ng-repeat to iterate through a list of divs and manually adding items to the JSON that is rendering these divs. My goal is to position the last div that I add in the JSON at the location where the mouse cursor is, while keeping the rest of the divs in their original positions without specifying the position in the JSON itself.

My initial approach involved something like this:

<div ng-repeat="contact in jsonContacts" style="left: {{lastX}}px; top: {{lastY}}px;"></div>

However, implementing this resulted in all the divs having the same position. Therefore, I need to create a conditional statement using the $last variable to dynamically apply or remove the style tag with the left and top CSS properties.

Thank you for your assistance, Daniel!

Answer №1

After analyzing your HTML, the following code snippet is recommended

<div ng-repeat='contact in jsonContacts' ng-style='{"left":($last?lastX:null)+"px","top":($last?lastY:null)+"px"}'>{{item}}</div>

You can check out this fiddle for confirmation http://jsfiddle.net/cmyworld/yFc6J/1/

Answer №2

Check out this fiddle to see examples of both methods (using color as position is more challenging in jsfiddle)

Approach 1: Utilizing ng-style and a Scope Function

With ng-style, you can achieve this effect. To maintain cleanliness and testability, it's recommended to define a scope function like the one below (ternary operators are currently not supported in angular expressions for stable versions of angular 1.0.x, though ternary support has been added in 1.1.5).

ng-style='myStyleFunction($last)'

In the controller, define:

$scope.myStyleFunction = function($last) {
  return {
    'left': $last ? $scope.lastX + 'px' : '',
    'top': $last ? $scope.lastY + 'px' : ''
  };
}

Approach 2: Creating Custom Directives

Alternatively, you can take a more "angular" approach by defining a directive:

dirModule.directive('positionLast', function() {
    return {
        scope: true,
        link: function (scope, $element, attrs) {
            if (scope.$last) {
              // If jQuery is available, use this. Otherwise, adjust accordingly
              $element.css("left", $scope.lastX + 'px');
              $element.css("top", $scope.lastY + 'px');
            }
        }
    }
});

and then:

<div ng-repeat="contact in jsonContacts" position-last> ...

EDIT This method works by using scope: true and declaring the directive on the ng-repeat element. Since only one new scope is created for all directives on an element (assuming at least one requests a new scope), it gains access to the ng-repeat scope values. Refer to the following documentation for more details:

scope - If set to true, a new scope will be created for this directive. If multiple directives on the same element request a new scope, only one new scope is created.

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

Navigating the world of cryptocurrency can be daunting, but with the right tools

Hello fellow developers, I've encountered some difficulties with cryptocurrency in my Nativescript project. I am attempting to incorporate the NPM package ripple-lib into my code, but I have been unsuccessful using nativescript-nodeify. How can I suc ...

How can I achieve a smooth background-image transition in Firefox?

Currently, I'm on the hunt for a substitute for this specific code snippet: "transition:background-image 1s whatever" This particular transition only seems to function on webkit browsers, leaving Firefox users out of luck. I experimented with utili ...

Unpredictable algorithm for selecting the champion

I manage a website that features promotions and users. Users have the ability to register for these promotions, with one random user selected as the winner. Initially, the formula for selecting the winner was quite simple: $total_users = 100; //total use ...

Angularjs Socket.io Integration

I am working on implementing websockets in my Angular/nodejs application using socket.io. My main goal is to maintain a "live" array on the server of documents that are currently unavailable for editing (due to someone else already editing them). I starte ...

Is there a way to use JavaScript or jQuery to automatically convert HTML/CSS files into PDF documents?

While using OS X, I noticed that in Chrome I have the option to Save as PDF in the print window by setting the destination to "Save as PDF". Is this feature available on Windows? Is there a way to easily save to PDF with just one click? How can I access t ...

Using the useState hook with an array of objects is not functioning as intended

I have initialized a useState object in my file like this: const [comments, setComments] = useState({ step_up: [], toe_walking: [], toe_touches: [], squat: [], side_to_side: [], rolling: [], leg_lifts: [], hand_to_knees: [], floo ...

Increase the padding on the left side of a background image

UPDATE: Solution discovered at this link thanks to Mr. Alien I am attempting to create a heading that resembles the following Title ------------------------------------------------- I have an image that I intend to use as a backdrop for it. However, I& ...

Transparent background with opaque text

I noticed that my div has a gray background with some opacity. <div className="absolute w-full h-full top-0 left-0 right-0 bottom-0 bg-slate-500 opacity-50 z-10"> <p className="relative top-1/2 px-8 text-center hea ...

Exploring the world of jQuery and Ajax: Experimenting with implementing a POST method through Ajax and retrieving the response in HTML

Hey guys, I'm currently attempting to set up a basic HTML post method using Ajax. Take a look at the code snippet below: <?PHP function fetchInstagramData($url) { $ch = curl_init(); curl_setopt_array($ch, array( CURLOPT_URL => ...

jQuery UI Accordion - Adjusting Panel Height to Content Size

Currently, I am utilizing jQuery UI's Accordion feature from http://jqueryui.com/demos/accordion/, and my goal is to adjust it so that it resizes based on the contents of each panel rather than just fitting the largest one. In addition, I am seeking ...

Concealing and revealing content using JQuery based on user input in

I'm attempting to create a feature where the visibility of a password field is determined by the value of another input element. For instance, when the username is set to "admin", the password field should be hidden. If any other value is entered in ...

The CSS cubic-bezier fails to smoothly transition back to its initial position

I created an animation that works perfectly when hovering over the target elements, however, it doesn't smoothly transition back to its original position when the cursor moves outside of the target element. Instead, it snaps back abruptly and unattrac ...

React dynamic dropdown selection based on previous dropdown values

I have implemented 3 react input fields that are populating data to a useState Hook <FormControl fullWidth> <InputLabel>Primary Goal</InputLabel> <Select ...

Issues with the Dropdown Menu

I'm currently working on a dropdown menu and I've encountered two issues. When I hover over the links in the main navigation bar (such as 'about' and 'connect'), only the actual words are clickable, not the entire area tha ...

Improving animation performance on mobile devices using AngularJS

I've reached the final stages of developing a mobile application using AngularJS wrapped in a cordova webview. However, I'm encountering some issues with the panel transition animations. After experiencing strange behavior with ngAnimate, I deci ...

Retrieve the URL of the image from an XML document

Figuring out how to extract the image URL from XML files in Android Studio can be challenging. After analyzing 30 RSS Feed XMLs, I discovered that 95% of them contain ".jpg" images with links starting with "http," not "www." Therefore, I am working on a co ...

Difficulty encountered when trying to obtain div height automatically

For a while now, I've been attempting to dynamically determine the height of an image as the browser window is adjusted. Despite using console.log() to verify my results, I keep getting a value of 0. What could be causing this discrepancy? $(functio ...

Learn the art of animating "basic jQuery filtering" exclusively with CSS

Does anyone have suggestions on how to animate elements when filtered by JavaScript? The code I've tried so far doesn't seem to be working. Here's what I currently have: http://jsfiddle.net/ejkim2000/J7TF4/ $("#ourHolder").css("animation", ...

Guide to redirecting data from an external POST request to a customer through a GET request

Within my Express application, I am currently dealing with both incoming POST requests containing a payload from an external source and GET requests sent by my client: router.post('/liveReleaseStore', (req, res) => { let data = req.body.m ...

Tap on the div nested within another div

Here is the scenario I am dealing with: <div id="main"> <div id="a"></div> <div id="b"></div> </div> On my website, element B is positioned below element A. How can I attach a click event only to those A elements t ...