我是Firebase的新手。我正在尝试使用Angular构建可编辑的TreeView,并将其内容保存到Firebase。内容存储在“树”模型中,该模型包含节点列表,每个节点包含其子节点列表等。
将此对象与FireBase同步的最简单方法是什么? 简单的3向绑定是否有效(只需使用。$ bind方法将我的模型绑定到firebase对象)?
这是我的代码。添加节点时,它当前会产生错误:
TypeError: Cannot call method 'push' of undefined
使用Javascript:
angular.module("myApp", ["firebase"]).
controller("TreeController", ['$scope', '$firebase', function ($scope, $firebase) {
var treeRef = new Firebase("https://flickering-fire-x.firebaseio.com/my-tree");
$scope.delete = function (data) {
data.nodes = [];
};
$scope.add = function (data) {
data.nodes.push({
text: "",
nodes: []
});
};
// Is this correct: ?
$scope.remoteTree = $firebase(treeRef);
$scope.remoteTree.$bind($scope, "tree");
}]);
HTML:
<script type="text/ng-template" id="tree_item_renderer.html">
<input type = "text" ng-model = "data.text" />
<button ng-click = "add(data)" > Add node </button>
<button ng-click="delete(data)" ng-show="data.nodes.length > 0">Delete nodes</button >
<ul>
<li ng-repeat = "data in data.nodes"
ng-include = "'tree_item_renderer.html'" ></li>
</ul>
</script>
<body ng-app="Application" ng-controller="TreeController">
<ul>
<li ng-repeat="data in tree" ng-include="'tree_item_renderer.html'"></li>
</ul>
</body>
答案 0 :(得分:0)
您尝试在添加功能中推送到 undefined 数组。
要避免此错误,您必须先创建数组才能使用它!
angular.module("myApp", ["firebase"]).
controller("TreeController", ['$scope', '$firebase', function ($scope, $firebase) {
var treeRef = new Firebase("https://flickering-fire-x.firebaseio.com/my-tree");
data.nodes = [];
$scope.delete = function (data) {
data.nodes = [];
};
$scope.add = function (data) {
data.nodes.push({
text: "",
nodes: []
});
};
// Is this correct: ?
$scope.remoteTree = $firebase(treeRef);
$scope.remoteTree.$bind($scope, "tree");
}]);
这将是工作
答案 1 :(得分:0)
我明白了 - 问题在于Firebase不会保存空数组,只是忽略它们。因此add函数应检查data.nodes是否未定义:
$scope.add = function (data) {
var newNode = {
text: "",
nodes: []
} ;
if(data.nodes){
data.nodes.push(newNode);
}else{
data.nodes = [newNode];
}
};