Custom AngularJS Directive for managing an array of Scope data

I have an array where each item contains data for a specific directive. This array is initialized within a controller.

The Model

$scope.myDirectiveData = 
          [ { title: "First title", content: "First content" }, 
            { title: "Second title", content: "Second content" } ];

The Directive Template

<div class="MyDirective">
   <h1>{{myDirectiveData.title}}</h1>
   <p>{{myDirectiveData.content}}</p>
</div>

How should I go about implementing the directive to create an instance for each item in the array? Something like...

<MyDirective data-ng-repeat="item in myDirectiveData"></MyDirective>

Answer №1

An illustration showcasing the usage of a directive is provided below. Utilizing ng-repeat, your directive is invoked for each object within the array on your scope. Is this what you were searching for? Check out the demonstration in the following fiddle:

http://jsfiddle.net/gLRxc/4/

angular.module('test', [])

.directive('myDirective', function () {
    var template = '<div class="MyDirective">' +
        '<h1>{{ data.title }}</h1>' +
        '<p>{{ data.content }}</p>' +
        '</div>';
    return {
        template: template,
        scope: {
            data: '='
        },
        link: function (scope, element, attrs) {

        }
    };
})

.controller('TestController', function ($scope) {
    $scope.myDirectiveData = [
            { title: "First title", content: "First content" },
            { title: "Second title", content: "Second content" }
        ];
})
;

The HTML has been altered - the ng-repeat now appears on the same line as the directive, addressing your query directly.

<div ng-app="test" ng-controller="TestController">
     <div my-directive data="item" ng-repeat="item in myDirectiveData"></div>
</div>

Answer №2

<div ng-repeat="element in myDataDirective">
  <h2>{{element.name}}</h2>
  <p>{{element.message}}</p>
</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

console rendering duplication in React

Why am I seeing duplicate log entries in the console? While working on another project, I noticed that the number of HTML elements being added using jQuery was twice as much as expected (specifically while building a notification framework). To investigate ...

Socketio: Issue: Isolated surrogate U+D83D is not a valid scalar value

I've been experiencing frequent crashes with my node.js server recently, all due to a recurring socket.io error. It seems that the client may be sending invalid UTF strings, causing an error in the utf8.js file. I'm getting frustrated with the co ...

Issues encountered while trying to implement HTML text within span tags

In my code snippet, I am using a span element: <span> {textToRender} </span> The purpose of this code is to render HTML text (as a string) within a span element. some text <br/> some text <br/> some text <ol>text However, wh ...

What could be causing the ng-repeat to remove the incorrect item when splicing?

I'm encountering an issue while trying to splice out items in this ng-repeat based on their $index. Although it works perfectly for adding items, when attempting to delete an item using the same code, it ends up removing only the last item of the arra ...

issue with accessing property in vue 2 simple examination

Hey there! I'm currently working on implementing Vue in a Laravel application, but I've run into some challenges. Essentially, my goal is to retrieve data from a GET request and generate results based on that data. However, I'm struggling to ...

Starting multiple JQuery UI sliders at once

Currently, I'm in the process of developing a template that may contain one or multiple JQuery UI Sliders. Is there a way to initialize all sliders using a single script if the settings for each slider are stored within data-options or data-id attrib ...

Exploring Typescript within React: Creating a property on the current instance

Within my non-TypeScript React component, I previously implemented: componentWillMount() { this.delayedSearch = _.debounce((val) => { this.onQuerySearch(val); }, 1000); } This was for debouncing user input on an input field. The corres ...

The presence of an unauthorized token within the meteor/node module has been detected, specifically related

While following g00glen00b's tutorial on meteor/twitter integration (), I encountered a persistent error. Any assistance or clues would be greatly appreciated. Steps I've Taken Uninstall/reinstall npm Uninstall/reinstall twitter package Uninst ...

conceal elements using the <option> class隐藏

Although it seems like a simple task, I'm struggling to make it work. I created a form where the user can select a month from a list using the tags: <select> <option> When the selection is changed, the class .gone from the day SELECT is ...

Animate the toggling of classes in jQuery

Here is a code snippet that I came across: $('li input:checked').click(function() { $(this).parent().parent().toggleClass("uncheckedBoxBGColor", 1000); }); This code is functioning correctly when the element is clicked for the first time. I ...

Encountering difficulties displaying a webpage in Express.js following a successful DELETE request

While working on a URL shortening project using Node.js, MongoDB, and ejs, I encountered an issue when trying to render a page after successfully handling a DELETE request. Although the 'deletion' page is loaded in the response preview in the bro ...

What is the best way to invoke a service within the angularJs configuration settings?

I'm encountering an issue with a service that needs to be called in the app's config module. It's throwing an error when I attempt to inject it. Strangely enough, this service functions perfectly when injected and executed in controllers. An ...

Accessing a JSON value within the AngularJS controller for the purpose of making edits

Seeking assistance here, as I work with a JSON file to generate a timeline using AngularJS. While I've successfully utilized the ng-repeat loop in HTML binding to display dates, I now need to modify the date format – specifically, changing "2013-01- ...

Using Ajax script to transfer user information to a php file in order to refresh the modified row in a table

Recently, I created a table in PHP to display certain data. Here's how it looks: <?php echo '<table id="tableteste" class="table table-striped" width="100%">'; echo '<thead><tr>'; echo &apos ...

Connecting one property of a JavaScript object to another property within the same JavaScript object

I am working with a JavaScript Object and I want to use the map() function to match the Id with another id in the same JavaScript Object. Here is the schema for my JavaScript Object: var items = [ { BossId: "03", DateOfBirth: "1966-09-27T00:00:0 ...

Create an interactive JSON tree structure

I am looking to create a JSON tree from an array. My array is structured like this: var arraySource = []; arraySource.push({key : "fr", value: "france"}); arraySource.push({key : "es", value: "spain"}); //... console.debug(arraySource); The desired JSON ...

Customizing MUI DataGrid: Implementing unique event listeners like `rowDragStart` or `rowDragOver`

Looking to enhance MUI DataGrid's functionality by adding custom event listeners like rowDragStart or rowDragOver? Unfortunately, DataGrid doesn't have predefined props for these specific events. To learn more, check out the official documentati ...

The only information returned from calling mongoose's Model.save() method are the fields { _id, __

I've encountered a problem even though I believe I'm following all the right steps. I'm attempting to save an item from a form into my mongodb collection using mongoose. This is what my schema looks like: // stationmodel.js export const Sta ...

What is the process of branching a stream with highland.js?

I have a stream called sourceStream that contains objects of type BaseData. My goal is to split this stream into n different streams, each filtering and transforming the BaseData objects according to their specific criteria. Ultimately, I want to end up ...

Is it more suitable for the response logic to be implemented within the saga or the reducer?

Consider this scenario: export function* incrementAsync(action) { try { const res = yield call(Api.signin.create, action.payload); yield put({ type: USER_SIGN_IN_FETCH_SUCCESS, payload: res.data.auth }); } catch (e) { yie ...