• 博客园logo
  • 会员
  • 周边
  • 新闻
  • 博问
  • 闪存
  • 众包
  • 赞助商
  • YouClaw
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
邹天得
博客园    首页    新随笔    联系   管理    订阅  订阅

前端之Angular2实战:内置指令中的ngFor

http://www.tuicool.com/articles/qEFje2q

时间 2015-09-24 10:46:55  SegmentFault
原文  http://segmentfault.com/a/1190000003786172
主题 AngularJS

Angular2 内置了许多新的指令,其中NgFor就是用来进行替换旧有的ng-repeat标签。关于Angular2开发进度可以查看 Is Angular 2 Ready? ,关于笔者的相关代码可以查看 这里 。

Angular1中展示列表数据的方式如下:

<!-- Angular 1.x -->
<ul>
    <li ng-repeat="item in items">
        {{$index}} {{item}}
    </li>
</ul>

而如果使用ng-for的话,如下所示:

<!-- Angular 2.0 -->
<ul>
    <li *ng-for="#item of items; #i = index">
        {{i}} {{item}}
    </li>
</ul>

Angular2引入了很多新的语法,其中 *ng-for 中的*是Angular2中template语法的缩写,如果是全部的话,应该为:

<!-- Angular 2.0 longhand ng-for -->
<template ng-for #item="$implicit" [ng-for-of]="items" #i="index">
    {{i}} {{item}}
</template>

在正常的开发中,基本上不会用到这种全语法,不过知道*表达式的意义还是很有必要的。template的作用在于防止浏览器读取或者执行内部标签,这样就能够保证Angular2安全地生成模板而不需要担心被XSS等。另一个常用的表达式为 #item of items; ,#表达式会创建一个局部变量以供在template内部使用。

一个完整的ngFor指令用法如下所示:

  • Component

//Typescript
class DisplayComponent {
  myName: string;
  names: Array<string>;
  constructor() {
    this.myName = "Alice";
    this.names = ["Aarav", "Martín", "Shannon", "Ariana", "Kai"];
  }
}
  • View

//Typescript
import {Component, View, bootstrap, NgFor} from 'angular2/angular2';
@View({
  template: `
  <p>My name: {{ myName }}</p>
  <p>Friends:</p>
  <ul>
     <li *ng-for="#name of names">
        {{ name }}
     </li>
  </ul>
`,
  directives: [NgFor]
})

当然,也可以将数据的获取写成依赖注入的模式,譬如我们创建了一个Service为:

class FriendsService {
  names: Array<string>;
  constructor() {
    this.names = ["Alice", "Aarav", "Martín", "Shannon", "Ariana", "Kai"];
  }
}

那么在Component中就需要引入:

@Component({
  ...
  appInjector: [FriendsService]
})
class DisplayComponent {
  myName: string;
  names: Array<string>;
  constructor(friendsService: FriendsService) {
    this.myName = 'Alice';
    this.names = friendsService.names;
  }
}
posted on 2017-05-03 23:27  邹天得  阅读(1455)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2026
浙公网安备 33010602011771号 浙ICP备2021040463号-3