2017-10-16 68 views
0

我是一名试图学习Angular和Ionic的C#程序员。 我想要做的事情,因为我们通常做的在C#中使用词典:Newbee in Angular,如何使用字典?

export class HomePage { 
    private times = [ 
    {key: 'clockOn', value: '09:00'}, 
    {key: 'lunchTime', value: '12:00'}, 
    {key: 'backToWork',value: '13:00'}, 
    {key: 'clockOff', value: '18:00'} 
    ]; 
} 

getHour(name: string) { 
    if(this.times[name] === 'clockOn'){ 
     console.log('time: ' + this.times[name].value); 
} 

在HTML

<ion-datetime class="time" id="coff" displayFormat="HH:mm" 
    [(ngModel)]="cOff" (ionChange)="getHour('clockOn')"> 
</ion-datetime> 

和Chrome控制台上我看到:

clockOn
不确定

首先,这是否正确sintax访问成员'价值'?

this.times[0].value 

我想知道,如果是可以用字符串作为索引(键)使用词典

例如访问数组元素,像我们一样在C#:

this.times['clockOn'].value //would bring me its value like '09:00' 

或访问元素的唯一方法是使用数字作为索引器?如下所示

this.times[0].key // bring me 'clockOn' 
this.times[0].value // bring me '09:00' 

回答

1

词典是Angular/JavaScript与C#无法相同。

所以,你的代码:

this.times['clockOn'].value 

这是不行的。

你将不得不使用

this.times[0].key // bring me 'clockOn' 
this.times[0].value // bring me '09:00' 

如果你想与像数组键访问[关键]返回值运行循环以这种方式:

<td *ngFor="(key, value) in dictionary"> 
    {{value}} 
</td> 

希望它能帮助。

0

就个人而言,我只是修改你的数据结构,如果他们只是硬编码的值。

private times = { 
     clockOn: '09:00', 
     lunchTime: '12:00', 
     backToWork: '13:00', 
     clockOff: '18:00' 
    }; 

    getHour(key: string) 
    { 
     if (this.times[name] === 'clockOn') 
     { 
      console.log('time: ' + this.times[name].value); 
     } 
    } 

    <span *ngFor="(key, value) in times" *ngClick=getHour(key)>{{value}}</span> 

拥有独特的键,您可以用括号符号查找所需的项目,其目的在于更有效,因为它允许快速简单的外观窗口。

如果您想使用原始数据结构,您必须传入重复项目的索引,以便可以访问数组中的正确项目。

让你的标记应该是这样的:

< span *ngFor="time in times" let i=index; *ngClick=getHour(i)>{{value}}</span>

​​