【发布时间】:2016-04-05 13:30:09
【问题描述】:
我遇到了一个地方,Angular2 上的模型绑定没有像我预期的那样绑定,并且我在确定哪里出错时遇到了问题。
我有一个对象数组如下:
commands = [
{
"id": 2,
"command": "!first",
"action": "This is the first command. You found it!",
"reply": false
},
{
"id": 5,
"command": "!hi",
"action": "Hello, how are you today?",
"reply": true
},
...
];
视图模板如下(为简洁起见,仅显示带有相关Angular2信息的标签):
<form #commandForm="ngForm">
<tr *ngFor="#cmd of commands">
<td *ngIf=" ! isEditingCommand(cmd)">{{ cmd.command }}</td>
<td *ngIf="isEditingCommand(cmd)">
<input type="text" class="form-control" placeholder="!command" required [(ngModel)]="cmd.command" (ngModelChange)="cmd.command=cleanCommand($event)" ngControl="cmd" #cmd="ngForm">
</td>
<td *ngIf=" ! isEditingCommand(cmd)">{{ cmd.action }}</td>
<td *ngIf="isEditingCommand(cmd)">
<textarea class="form-control" rows="1" placeholder="Text to display." required [(ngModel)]="cmd.action" ngControl="action" #action="ngForm"></textarea>
</td>
</tr>
</form>
isEditingCommand(cmd) === false时,行显示如下:
当isEditingCommand(cmd) === true时,这是我得到的:
我已将cmd 和cmd.command 更改为各种名称,以防command 是Angular2 的保留字,但无济于事。当我将{{ cmd | json }} 放在视图中时,我收到此异常:
EXCEPTION: TypeError: Converting circular structure to JSON in [
{{ cmd | json }}
in CommandComponent@24:199]
很遗憾,我无法确定它如何具有圆形结构。即使通过 Chrome Inspector,我也找不到可能是圆形的地方。
为了提供帮助,以下是视图中定义的函数(TypeScript 给我带来了问题;稍后我将对其进行重构):
CommandComponent.prototype.cleanCommand = function (value) {
value = value.replace(/[^a-z]+/gi, '');
if (0 >= value.indexOf('!') && '!' !== value.substr(0, 1)) {
value = '!' + value;
}
return value;
};
CommandComponent.prototype.isEditingCommand = function (command) {
if (null === this.currentCommand) {
return false;
}
return this.editFormActive && this.currentCommand.id === command.id;
};
// These are not used by the template shown, but they set values used in the functions.
CommandComponent.prototype.editCommand = function (command) {
this.editFormActive = true;
this.currentCommand = command;
};
CommandComponent.prototype.cancelEditCommand = function () {
this.editFormActive = false;
this.currentCommand = null;
};
环境:
- Angular 2.0.0-beta.13
- RxJS 5.0.0-beta.2
- Zone.js 0.6.8
我做错了什么?如果需要更多信息,请告诉我,谢谢!
【问题讨论】: