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

Guide to building a personalized autocomplete feature in vue js

Presently, I am using the buefy autocomplete feature, but it is causing a few problems. In the DepartmentDetail.vue file <template slot-scope="props"> <div class="container is-fluid"> <b-loading :is-full-page=" ...

After AJAX has been loaded, Readmore.js fails to function properly

I am currently struggling to get the Readmore.js plugin working with AJAX content. The code snippet I have included is not cutting off the content inside the .more element as expected. <td><div class="more"><?php echo $row['book_desc&a ...

Automatically retrieve the generated PDF file upon completion (Node.js and Express)

I've been utilizing the node module html-pdf to seamlessly convert my HTML into PDF format. The conversion process goes smoothly, but I'm encountering difficulties when it comes to downloading the file once it's been generated. Below is the ...

What is the best way to include text in an editor access notification email?

I've developed a script to assign editors to a spreadsheet, but I'm looking to personalize the emails sent to them. The screenshot below illustrates the step where I can input a message for the email recipients who have been granted access. f ...

No JSON data retrieved by Ajax in Controller

I'm facing an issue with my controller where the String formData is null when I try to catch the post data. This results in me not being able to use the Anti Forgery Attribute as it seems like all the data is lost. Could it be that using serializeArra ...

Using Joomla 2.5 and mootools for ajax - passing parameters to a component

After countless hours of searching for a solution to this persistent issue, I find myself stuck with the following code in a standard component along with its controller: defined('_JEXEC') or die; jimport('joomla.application.component.cont ...

Neglecting asynchronous Ajax functions once they have been called

I currently have a function that looks like this: $("#transfer").click(function(){ var token_rec = $("#token_rec").val(); var user_rec = $("#user_rec").val(); var subdomain_rec = $("#subdominio_rec").val(); var req_rec ...

Feeling puzzled by the code snippet for vuejs-templates using webpack-simple?

Just starting out with javascript. Learning Vue.js through example reading. But feeling confused by the code snippet from vuejs-templates/webpack-simple. Specifically line 25 data () { return { msg: 'Welcome to Your Vue.js App' ...

Exploring nested JSON information through jQuery's AJAX call

I am encountering an issue with accessing JSON data using a jQuery AJAX request in JavaScript. I keep receiving a 'Cannot read property [0] of undefined' error in the console of Google Chrome. Despite trying different approaches, such as referrin ...

Tips for aligning a Bootstrap container in the middle of the viewport vertically

I'm struggling to center a Bootstrap container vertically in the viewport. You can view my code at http://www.bootply.com/C8vhHTifcE All of my attempts at centering have been unsuccessful. Does anyone have a solution? Just to clarify: I want the co ...

Error: Attempting to access a property of an undefined value (referencing '8') was unsuccessful

Hello everyone, I am new to posting and identify as a junior Frontend developer. I'm encountering a confusing issue with the InputLabel from Material UI (ver. 5) on a specific section of the website I'm working on. On the homepage, I successfully ...

What is the best method for converting a string picture URL into an image and showcasing it in an image tag?

I have a URL for an image that looks like this: C:\inetpub\MaujApp\OMSAPI\ManualReceivingImages\WhatsApp Image 2021-03-24 at 12.07.41 PM.jpeg My goal is to convert the original image and display it to the user using jQuery. I woul ...

When creating a PDF from HTML using iText, the CSS styling is not applied

Even though I am able to generate a PDF from an HTML string, the issue is that it doesn't apply the CSS styles. How can I create a PDF with CSS styling? Please assist! I have already attempted using CSSResolver. Below is my code snippet: {String res ...

Retrieving XML data from an external API is essential for integrating information

For a personal project, I am working on a mashup and trying to integrate a webservice that I came across. You can find the webservice here: Whenever I attempt to call it via ajax (using FireFox 7 in this case), I constantly encounter the following error ...

Instructions on how to dynamically show specific text within a reusable component by utilizing React and JavaScript

My goal is to conditionally display text in a reusable component using React and JavaScript. I have a Bar component that I use in multiple other components. In one particular ParentComponent, the requirement is to show limit/total instead of percentage va ...

Changing a multidimensional object array into a standard array

Hey there, I've mastered how to retrieve errors from Laravel validation, but now I'm facing a challenge in displaying them. I'm looking for a straightforward way to iterate through each error message and present it on the user's page us ...

Getting the true height without needing jQuery

let element = document.getElementById('test'); console.log(element.scrollHeight); <div style="height: 30px;" id="test"> <p>ffffffffff</p> <p>gggggggggg</p> ...

What are the steps to secure an API endpoint using PassportJS?

Within my app, I have integrated Express and AngularJS for functionality. Specifically, I am utilizing express to manage the basic web serving of the angular code through static routes. The angular code interacts with services that connect to API endpoin ...

The current date object in JavaScript will only display the year or a combination of the month and

$scope.articles = [ { link: "http://google.com", source: "Google", title: "hello", "date": new Date(2008, 4, 15) }, ]; <tbody> <tr ng-repeat = "article in articles | orderBy:sortType:sortReverse | filter:searchArticle ...

Tips for positioning a hero image perfectly using HTML and CSS

I am looking to display two hero images on the index page and wondering how to align them. My goal is to have both images centered with 50px separation under the header, ensuring they are of equal height. Will using the flex property work for hero images? ...