4

i've a array. Every item of the array holds data for an directive. The array is created inside 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 implement the the directive to create a item for any item in the array ? Something like...

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

2 Answers 2

4

Here is an example using a directive. It used ng-repeat to call your directive for each object in the array on your scope. In this fiddle is this what you are looking for.

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" }
        ];


})
;

Html Edited: the ng-repeat is on the same line as the directive like your question states.

<div ng-app="test" ng-controller="TestController">
     <div my-directive data="item" ng-repeat="item in myDirectiveData"></div>
</div>
Sign up to request clarification or add additional context in comments.

Comments

0
<div ng-repeat="item in myDirectiveData">
  <h1>{{item.title}}</h1>
  <p>{{item.content}}</p>
</div>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.