AngularJS Directive with Scope Dataset

I have an array. Each element of the array contains data for the directive. An array is created inside the controller.

Model

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

Directive Template

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

How do I implement a directive to create an element for any element of an array? Sort of...

<MyDirective data-ng-repeat="item in myDirectiveData"></MyDirective>
+4
source share
2 answers

Here is an example of using the directive. He used ng-repeat to call your directive for every object in the array in your area. In this fiddle, this is 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: ng-repeat is on the same line as the directive similar to your request.

<div ng-app="test" ng-controller="TestController">
     <div my-directive data="item" ng-repeat="item in myDirectiveData"></div>
</div>
+4
source
<div ng-repeat="item in myDirectiveData">
  <h1>{{item.title}}</h1>
  <p>{{item.content}}</p>
</div>
0
source

All Articles