我最近从 angularfire 0.6 切换到 0.8.0。我在保存包含数组本身的列表项时遇到问题。
我的对象account看起来像这样:
{
"-JQruasomekeys0nrXxH" : {
"created" : "2014-03-23T22:00:10.176Z",
"durations" : [ {
"$$hashKey": "00L", // this is generated by ng-repeat on arrays
"end" : "2014-07-15T22:00:00.000Z",
"start" : "2014-07-09T22:00:00.000Z"
} ],
"email" : "[email protected] /cdn-cgi/l/email-protection",
}
}
持续时间是一个包含开始和结束时间段的数组,类似于 HTML 中两个输入字段的 ng-repeat。
<tr ng-repeat="duration in account.durations">
<td>
<input ng-model="duration.start" datepicker>
</td>
<td>
<input ng-model="duration.end" datepicker>
</td>
</tr>
在将帐户保存到 firebase 之前,我在控制器中执行 angular.copy($scope.account) ,以摆脱角度 $$hash 值。这在 angularfire 0.6.0 中有效。
在 angularfire 0.8.0 中,我仍然收到错误:
错误:Firebase.set 失败:第一个参数包含无效密钥
($$hashKey) 在属性“durations.0”中。键必须是非空字符串
并且不能包含“.”、“#”、“$”、“/”、“[”或“]
当使用内部有数组的对象时,这意味着如何通过 AngularFire 来解决这个问题?持续时间不会是我在帐户中拥有的唯一数组。那么有没有更专业的解决方案,或者我是否必须在通过 AngularFire 保存到 Firebase 之前复制每个数组对象?
预先感谢您的任何提示。
更新(2014 年 8 月 11 日)经过更多研究后,问题不在于使用 angular.copy() 不再起作用。事实上确实如此。但是使用 AngularFire 方法 $save() 更新/修改现有数据集非常不方便(https://www.firebase.com/docs/web/libraries/angular/api.html#angularfire-firebaseobject-save https://www.firebase.com/docs/web/libraries/angular/api.html#angularfire-firebaseobject-save)因为在执行 angular.copy() 之后我似乎无法找到 $save() 项目的正确方法。
更新 2(2014 年 8 月 12 日)我暂时找到了一个解决方法,但实际上我首先想避免的是解决方法:
// loop for every duration, that should clean the object from "$$hashKey" attributes
angular.forEach($scope.account.durations, function (value, index) {
var cleanValue = {};
// checks, if the date is a JSON string already
if (typeof value.start === 'string') {
cleanValue.start = value.start;
} else {
cleanValue.start = value.start.toJSON();
}
// checks, if the date is a JSON string already
if (typeof value.end === 'string') {
cleanValue.end = value.end;
} else {
cleanValue.end = value.end.toJSON();
}
// overwrite the array object at index to get loose of $$hashKey
$scope.account.durations[index] = cleanValue;
});
我认为这种解决方法利用了 Firebase 中基于文档的原则的优势,因为在通过 AngularFire 存储对象之前我必须知道对象的确切属性。
更新 3(14 年 8 月 13 日)我添加了一个 jsfiddle 来显示问题:jsfiddle.net/1fem6byt http://jsfiddle.net/1fem6byt
如果您向数组添加行,然后尝试将对象保存到 firebase,则控制台中会出现 $$hashKey 错误(上面给出)。有多种方法可以解决这个问题,但如果可能的话,我正在寻找一种更简单或更干净的 AngularFire 解决方案。我可能无法正确添加行——或者我错过了什么?