最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - AngularJS Directive with Scope data array - Stack Overflow

programmeradmin1浏览0评论

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>

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>
Share Improve this question asked Sep 23, 2013 at 16:43 MR.ABCMR.ABC 4,86213 gold badges47 silver badges89 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 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/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>
<div ng-repeat="item in myDirectiveData">
  <h1>{{item.title}}</h1>
  <p>{{item.content}}</p>
</div>
发布评论

评论列表(0)

  1. 暂无评论