繁体   English   中英

带有Scope数据数组的AngularJS指令

[英]AngularJS Directive with Scope data array

我有一个阵列。 数组的每个项都包含指令的数据。 该数组在控制器内创建。

该模型

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

指令模板

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

我应该如何实现该指令为数组中的任何项创建项? 就像是...

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

以下是使用指令的示例。 它使用ng-repeat为作用域中数组中的每个对象调用指令。 在这个小提琴这就是你要找的东西。

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:ng-repeat与指令在同一行上,就像您的问题所述。

<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>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM