Iterating over ng-repeat, the initial item with a distinct directive

I have this code snippet:

<div ng-repeat="i in placeholders" square class="set-holder {{i.class}}" droppable="{{i.type}}"></div>

How can I ensure that the first item has the directive bigsquare, while the rest have just square?

I attempted:

<div ng-repeat="i in placeholders" {{= $first ? 'big' : ''}}square class="set-holder {{i.class}}" droppable="{{i.type}}"></div>

Unfortunately, the result I get is:

<div ng-repeat="i in placeholders" {{= $first ? 'big' : ''}}square class="set-holder test" droppable="3"></div>

Meaning, the binding does not get compiled.

Answer №1

If you want to iterate through a list using AngularJS, you can utilize the ng-repeat-start and ng-repeat-end directives. Here's an example of how to use them:

angular.module('example', [])
  .controller('ctrl', function Ctrl($scope) {
    $scope.items = [1, 2, 3];
  })
  .directive('big', function() {
    return {
      restrict: 'A',
      link: function(scope, element, attrs) {
        element.css('font-size', '30px');
      }
    };
  });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="example" ng-controller="ctrl">
  <div ng-repeat-start="item in items" ng-if="$first" big>
    big item {{item}}
  </div>
  <div ng-repeat-end ng-if="!$first">
    item {{item}}
  </div>
</div>

For more information, you can refer to the documentation available at ng-repeat.

Answer №2

Check out this example on JSFiddle: http://jsfiddle.net/nicolasmoise/xLfmK/2/.

An innovative approach is to create a single directive where a condition is passed. This directive will dynamically display either a square or a large square based on the condition.

<div ng-repeat="repeat in repeater" condition="$first" square></div>

Important to note: If you prefer not to modify your existing directives, you can implement square as a main directive that orchestrates the behavior of the other two directives.

Answer №3

If you are open to using an additional <div> within your <li>, you can achieve conditional blocks of <div> by utilizing ng-if="$index == ??".

Consider implementing something along these lines:

<div ng-repeat="i in placeholders">
  <div bigsquare class="set-holder {{i.class}}" droppable="{{i.type}}" ng-if="$index == 0">
    ...
  </div>
  <div mediumsquare class="set-holder {{i.class}}" droppable="{{i.type}}" ng-if="$index == 1">
    ...
  </div>
  <div square class="set-holder {{i.class}}" droppable="{{i.type}}" ng-if="$index > 1">
    ...
  </div>
</div>

Although a bit more verbose, this approach neatly segregates the templates, allowing for greater independence between them.

Answer №4

<!-- This is a snippet of code that I implemented in one of my angularjs ionic projects. -->
<!-- Using ng-repeat with additional logic -->
<!-- Checking for $first to apply special behavior with <input focus-input> -->
<ion-item class="item item-input item-stacked-label" ng-repeat="input in template.inputs">
  <label class="input-label bh-dark" for="{{input.id}}">{{input.title}}</label>
  <div class="clearfix">
    <div class="bh-left">
      <input ng-if="$first" focus-input id="{{input.id}}" type="{{input.type}}" placeholder="{{input.choices[0]}}" ng-model="input.answer">
      <input ng-if="!$first" id="{{input.id}}" type="{{input.type}}" placeholder="{{input.choices[0]}}" ng-model="input.answer">
    </div>
    <div class="bh-right">
      <i class="icon ion-ios-close-empty bh-icon-clear" ng-click="clearField(input.id)" ng-show="input.answer"></i>
    </div>
  </div>
</ion-item>

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

What is the best way to utilize JSON data in React components?

I am looking to showcase a collection of icons similar to what I saw on this particular website. Within my JSON data, I have stored both the family and name values for these icons. What I aim to do is map this JSON data in order to pass the family and nam ...

Convert an array into individual objects and include key-value pairs from a separate object

I am working with two arrays that have the same length: One is a simple array numbers = [4,5,6] The other is an array of objects objects = [ {type: "x", value: 7}, {type: "y", value: 8}, {type: "z", value: 9} ] My goal is to combine th ...

Poor initial placement of the Dialogs when the content exceeds the space available

While using material-ui^0.20 with react^16.2, I encountered an issue when initially displaying a Dialog containing a Component with excessive content. The problem is illustrated in this image: https://i.sstatic.net/RF8Mu.png This is the expected appeara ...

Vue.js event handlers

I am in the process of creating a basic app that will include a few listeners. However, I am struggling to determine the best approach for organizing the logic behind it. Here is an example of the HTML: <div id="playerProgressBar"> <div id=" ...

Center the image within the div by setting its position to absolute

<div class='img-box'> <img /> //position absolute <img /> //position absolute <img /> //position absolute <img /> //position absolute I am struggling to center the images within this div because of their absolute p ...

Display content based on specific categories from a JSON file using AngularJS

I am looking to display a list of products categorized that are coming in a json using Angular. The json data I have is: { "MAIN MENU ": [{ "id_prod": "1", "name_prod": "Artisanal chicken nuggets with mustard sauce", "descrip_ ...

Possible rewrite: "Unable to use jQuery to add elements to data fetched through AJAX requests."

I am looking to add a button to copy code inside every div that has a class starting with language. The code is functioning properly, however, after attempting to retrieve data from the database using Ajax, the button no longer appears in the div as it did ...

Learn how to use Javascript and ASP.NET to refresh the parent page in Mozilla Firefox browser

The code window.opener.location.reload(); works well in Internet Explorer, but it doesn't refresh the parent page in Mozilla Firefox. Can someone please advise me on how to refresh the parent page in a way that is cross-browser compatible? Here is th ...

Is there a feature in JavaScript that allows for the creation of URLs?

I created an index view displaying cards (like playing cards) in a grid using BootStrap. Each card is within its own div element, and I implemented a jQuery click handler for each div to open a details page when clicked. The redirect from the index to the ...

Is it necessary to convert an HTMLCollection or a Nodelist into an Array in order to create an array of nodes?

Here we go again with the beginner guy. I'm working on this exercise from a book called "Eloquent JavaScript". The goal is to create a function similar to "getElementByTagName". However, the first function below is not returning anything and the secon ...

The query does not produce a match when using the LIKE operator with the retrieved ajax data

My goal is to sync up profiles in my MySQL database with the names and skillsets dropped into my droppable div. At this link, you can find a snippet of code for reference. I am facing two main issues - firstly, the error message mysql_fetch_array() expects ...

What is the best way to calculate the number of div elements with a specific class that are contained within parent div elements with another specific class?

Is there a way to count the number of elements with the class '.child' in each container and then add a sentence containing that count inside each container? <div class='container'> <div class='child'></di ...

Guide on integrating a third-party API with React using Express

I'm facing an issue with my React app trying to make a get request to my Express app, which then sends a get request to a third party API to fetch stock prices. Even though the Express app is logging the correct data, I am getting an empty response fr ...

Highcharts - Troubleshooting the chart reflow feature

Take a look at the fiddle I created. I encountered an issue with the chart width when toggling the sidebar. After seeking help on Stack Overflow from this post, I was able to solve it. Now, I'm facing another bug where adding transitions while togg ...

Is it possible to use jQuery to load content and notify the calling window?

I am implementing the JQuery event "load" to detect when the full HTML window has finished loading along with all scripts being executed. I know this function is typically used within the document.ready event. However, my scenario involves a parent window ...

Utilizing JSON format for processing HTTP requests in JavaScript with Node.js

I'm working with a snippet that retrieves data in JSON format, but I'm interested in manipulating the data instead of just outputting it to the console. var request = require('request'); var headers = { 'Connection': ' ...

Performing CRUD operations with mongoose and express

My express app is currently being developed with mongoose, and the goal is to integrate it with React for the front end. In my customer controller, I have outlined some CRUD operations, but there are aspects of this approach that I find unsatisfactory. W ...

Continuously receiving the "Add to home screen" prompt despite already installing the PWA app

Is there a method to determine if the Progressive Web App has already been installed? It is possible to cancel the prompt event in the 'beforeinstallprompt' event. window.addEventListener('beforeinstallprompt', (event) => { // co ...

TypeError thrown by Basic TypeScript Class

I'm encountering an issue where TypeScript is throwing a TypeError when trying to use the class Literal from file Classes.tsx in file App.tsx, even though they are in the same file. Strangely, everything works fine on typescriptlang.org/play. // Class ...

Issue with bootstrap: the ID is not activating even when it is visible

I am a beginner with bootstrap and I encountered an issue. I created a simple page using bootstrap 5 and included 4 buttons: "Home," "Explore," "Create," and "Share." Here is the code for reference: https://github.com/nguyencuc2586/project2 In the code s ...