用于显示链或消息的Angular指令

时间:2015-10-29 06:46:19

标签: javascript angularjs

有以下HTML标记:

<section class="correspondence">
  <header>
    <div class="from">{{ message.from }}</div>
    <div class="when">{{ message.when }}</div>
  </header>
  <div class="content">
    {{ message.content }}
    <section class="correspondence">
    ...
    </section>
  </div>
</section>

正如你所看到的,这是一个标记有嵌套重复内容(字母链) - 我想打印消息数组$ scope.messages。我该怎么做?我想我应该为它制定一些指令。你能帮助我吗?谢谢!

2 个答案:

答案 0 :(得分:2)

试试这个........ 你需要使用ng repeat

HTML code same.and添加以下脚本代码。

var app = angular.module('myApp', []);
app.controller('formCtrl', function($scope) {
    $scope.messages = [{
        from: "test_from_1",
        when: "test_when_1",
        content: "test_content_1"
    }, {
        from: "test_from_2",
        when: "test_when_2",
        content: "test_content_2"
    }];

});

答案 1 :(得分:0)

这是一个有效的例子:http://plnkr.co/edit/dZ473fpX9BrxjPH3Cb3L?p=preview

在控制器中:

$scope.messages = [{
    from: "from_1",
    when: "when_1",
    content: "content_1"
}, {
    from: "from_2",
    when: "when_2",
    content: "content_2"
},{
    from: "from_3",
    when: "when_3",
    content: "content_3"
}];

在html中,使用ng-repeat循环数组(这将创建与消息一样多的部分):

<section ng-repeat="message in messages" class="correspondence">
  <header>
    <div class="from">{{ message.from }}</div>
    <div class="when">{{ message.when }}</div>
  </header>
  <div class="content">
    {{ message.content }}
    <section class="correspondence">
    ...
    </section>
  </div>
</section>