What is the best way to create a directive that wraps the div elements utilized in an ng-repeat loop?

When working on my application, I utilize this HTML snippet for an ng-repeat:

    <div class="gridBody">
        <div ng-class="{clicked: row.current == true}"
             ng-click="home.rowClicked($index)"
             ng-dblclick="ctrl.rowDoubleClicked(row)"
             ng-repeat="row in home.grid.view = (home.grid.data | orderBy:ctrl.examOrderBy[ctrl.configService.admin.examOrderBy].key:ctrl.configService.admin.examSortDirection) track by row.examId">

While I am familiar with creating template directives, I am unsure if it's possible to create a directive that calls another directive like how ng-repeat is called here. How would I go about creating a directive that allows me to use the code block in this manner:

    <div grid-body
         order="ctrl.examOrderBy[ctrl.configService.admin.examOrderBy].key"
         direction="ctrl.configService.admin.examSortDirection)"
         track="examId">

Essentially, I want a directive that combines the two <div>'s above into one. It seems like using transclude might be necessary, but I am unsure of how to implement it in this context as I couldn't find any relevant examples.

Answer №1

If you want to achieve isolation, Isolate Scope is the way to go

Feel free to take a look at my Plunker example

In my code, I also utilize ng-repeat:

<div employeeform ng-repeat="emp in emplList" passed-model="emp">
</div>

I've created an attribute directive called employeeform with its own isolated scope and controller:

empApp.directive('employeeform', [
  function($compile) {

    function RowController($scope) {
      $scope.smyClass = "none";
      $scope.clickMe = function() {
        if ($scope.smyClass == "none") {
          $scope.smyClass = "clicked";
        } else {
          $scope.smyClass = "none";
        }
      };    
    }

    return {
      restrict: "A",
      controller: RowController,
      replace: true,
      scope: {
        passedModel: '='
      },
      templateUrl: "Employee.html"
    };
  }
]);

The template Employee.html contains references to the controller's local scope functions and smyClass property:

<div class="{{smyClass}}" ng-click="clickMe()" >
  <div style="display:inline-block; width: 100px;">{{ passedModel.name }}</div>
  <div style="display:inline-block; width: 100px;">{{ passedModel.position }}</div>
  <div style="display:inline-block; width: 100px;">{{ passedModel.salary }}</div>
</div>

In the absence of your data, I have constructed a basic tabular report. Clicking on a row changes its background to yellow, providing a simulation of toggling.

To summarize:

When a directive boasts a distinct local scope:

  scope: {
    passedModel: '='
  },

it remains independent from the parent scope except for the specified parameters (such as passedModel). This setup allows for the use of local variables to define the characteristics of each individual row (directive).

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

How much space should be left from the edge for jQuery UI dialog to be

Typically, a dialog is centered using the following code: $(el).dialog('option', 'position', 'center'); Is there a method to specify a "minimum" distance from the side? For example, ensuring that the top position is always a ...

Trouble with Ajax loading asynchronously - webpage refreshing upon form submission

I am currently learning about ajax, and it seems like my code is correct. However, I am facing an issue where the page always refreshes when displaying the returned JSON string. Any assistance on this matter would be greatly appreciated! <script> ...

The JSX in React won't display the modified state on the user interface

In my diary object, I have records of 2 meals function Magicdiary() { const [diary, setDiary] = React.useState<MagicDiaryDay[]>([ { mealName: "Breakfast", ingredient: null }, { mealName: "Lunch", ingredient: null }, ]) ...

What mistakes am I making in this PHP code as I try to work with the select option?

Currently, I am developing a form that involves selecting values. If the user chooses 'yes', I want to display a text box section. However, the code below is not functioning as expected. <select id="gap" name="gap" onclick="gap_textbox();"> ...

Unable to access localStorage

I created a Plunker to store a value in localStorage: <!DOCTYPE html> <html> <script> localStorage.setItem('test', "hadddddha"); </script> </html> Then, I built a test page to retrieve the value from local ...

Is it possible to use Selenium with Python for copying and pasting

Is there a way to use control + A in Selenium Python to select text and then retrieve the highlighted text? ...

Implementing Ajax Js to search within a specific div - reducing text overload on the page

Our e-shop on Prestashop requires an Ajax search feature to find compatible batteries and adapters on the page. Here is the code I have created: https://jsfiddle.net/fgfjo2n9/ I am facing two issues: • 1st I want the output to only display the heading ...

How to clear a particular select option in react-bootstrap

I am looking for a solution to clear the second select when the first one selects option B. The clearing should involve removing the value, disabling it, and setting the default option to Select.... import React, { useState } from "react"; import ...

What is preventing jQuery 3 from recognizing the '#' symbol in an attribute selector?

After updating my application to jQuery 3, I encountered an issue during testing. Everything seemed to be working fine until I reached a section of my code that used a '#' symbol in a selector. The jQuery snippet causing the problem looks like th ...

Utilizing URL encoding instead of JSON when using Postman

I've hit a roadblock - I've spent almost the whole day trying to solve this issue. We are working on integrating csrf security into our website, which is built with play framework 2.5.9 and angularjs 1.x. I've added the csrf components and t ...

Tips for utilizing getServerSideProps with a series of consecutive fetch() promises?

I've encountered a CORS issue while working on my project, particularly with the second fetch (fetchURL2) being blocked due to the absence of the 'Access-Control-Allow-Origin' header. How can I resolve this CORS policy error using next.js ge ...

Creating my website with a unique inverse color scheme

I'm looking to change the color scheme of my webpage so that it is inverse (white becomes black and black becomes white) similar to the Dark Reader chrome extension: https://chrome.google.com/webstore/detail/dark-reader/eimadpbcbfnmbkopoojfekhnkhdbiee ...

Importing a file using its absolute path in JavaScript

Within the dependencies directory, there exists a module named foo: import foo from '../dependencies/foo'; // This import statement works as intended The challenge arises when attempting to import from a different path due to deployment in an AW ...

Using JavaScript to post data to a PHP script, then triggering the execution of another

My website has two distinct pages with different purposes. On one page, there is a button that, when clicked, sends data to finalizecontract.php. The other page, contract.php, creates a TCPDF form populated with the database information and saves the resu ...

Developing a Node.js and Express REST API for generating tailored routes for custom fields

I'm currently using node.js and express framework to build my REST API server. One of the features I want to implement is similar to the Facebook graph API, where I can pass specific fields in my API routes like: /me?fields=address,birthday,email,do ...

Strategies to manage or prevent a timezone offset while deploying a Next.js application on Vercel

Is there a way to ensure that a React/Next.js App always displays the local time in CEST, regardless of the user's location? For example, if I receive GMT time from the backend and want to offset it to display the CEST timezone, how can I achieve this ...

CKEditor not functioning properly when generated using AJAX and PHP in JavaScript file

I am facing an issue where I am using PHP and AJAX to generate a CKEditor textarea. The CKEditor JavaScript files are included in the main HTML file, and the PHP and AJAX functionalities are working correctly. However, when the form is displayed, the CKEdi ...

Having issues getting Nunjucks templates to render correctly in Express

There seems to be an issue with setting up the template hierarchy in Express or possibly an error in how Nunjucks is being utilized. The goal is to have a template that includes common parts and specific pages that extend this template. It appears that the ...

Issue with activating a Modal through a button inside a table row on React

I'm currently working on two files: Modal.js and Users.js. Users.js features a table with an API get query linked to it, and in the last column of the table, there's a dropdown for each row that contains three buttons: View, Edit, and Delete. My ...

Error 400: Invalid Request: Issue encountered when swapping code for Asana access token using Next.js

Encountered a 400 Bad Request error while trying to exchange the code for an access token at . I am unsure of the cause and would appreciate any assistance. Below is the code: const GetAsanaAccessToken = async (req, res) => { const body = { grant ...