[英]Surprising error message in Angular Dart relating to watchers
我正在編寫一個接受String並將其轉換為<span>
列表的組件。 每個<span>
都有一個String字符,並分配有隨機顏色。
組件調用如下所示:
<span ng-repeat="char in ctrl.chars" style="color: {{ctrl.randomColor}};">
{{char}}
</span>
組件定義如下所示:
import 'package:angular/angular.dart';
import 'dart:math';
@NgComponent(
selector: 'tokens',
templateUrl: './component.html',
cssUrl: './component.css',
publishAs: 'ctrl',
map: const {
'text' : '@text',
}
)
class TokensComponent {
String text;
List<String> get chars => text.split('');
String get randomColor {
var colors = ['red', 'green', 'yellow', 'blue'];
return colors[new Random().nextInt(colors.length)];
}
}
這可行,但是會產生錯誤:
5 $digest() iterations reached. Aborting!
Watchers fired in the last 3 iterations:
...
對我來說,目前尚不清楚我正在定義的吸氣劑之外正在觀察什么。 如果我將涉及Random
的代碼留在getter中,而僅返回一個硬編碼的String,則錯誤消息就會消失。
知道這里有什么問題嗎?
將getter方法與隨機返回值綁定在一起,似乎要求發生各種奇怪的事情。
從我看來,您的意圖似乎是用不同的隨機顏色顯示字符串的所有字符-但不能更改顏色(這意味着字符不應不斷更改其顏色)-是嗎?
不幸的是, <span>
不僅是使用randomColor
的當前返回值randomColor
,然后被遺忘了-綁定屬性的優點是,對屬性的更改會反映在視圖中。 當然,由於“屬性”是一個吸氣劑,並且具有隨機返回值,因此它會不斷變化,從而導致視圖不斷更新。
如果不會發生此錯誤以防止此無限循環,則所有字符可能都具有相同(快速變化)的顏色。
編輯
這個問題可以很好地回答這個問題: AngularDart自定義過濾器call()方法需要冪等嗎?
和替代方法:
原版的
我不確定您要達到什么目標,但無論如何還是有幫助的
結果截圖:
library main;
import 'dart:math';
import 'package:angular/angular.dart';
import 'package:di/di.dart';
class MyAppModule extends Module {
MyAppModule() {
type(TokensComponent);
}
}
void main() {
ngBootstrap(module: new MyAppModule());
}
@NgComponent(
selector: 'tokens',
template: '''<span ng-repeat="item in ctrl.items" style="color: {{item.color}};">
{{item.char}}
</span>''',
//cssUrl: './component.css',
publishAs: 'ctrl',
map: const {
'text' : '@text',
}
)
class TokensComponent {
String text = 'abcdefg';
List<Item> items = new List<Item>();
TokensComponent() {
text.split('').forEach((e) => items.add(new Item(e, randomColor)));
}
var colors = \['red', 'green', 'yellow', 'blue'\];
String get randomColor {
return colors\[new Random().nextInt(colors.length)\];
}
}
class Item {
Item(this.char, this.color);
String char;
String color;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.