如何在AngularJS到Firebase的数组中添加、删除和编辑新对象
我在一个控制器中有这些功能。我成功导入了数据,但无法使用如何在AngularJS到Firebase的数组中添加、删除和编辑新对象,angularjs,firebase,angularfire,firebase-realtime-database,Angularjs,Firebase,Angularfire,Firebase Realtime Database,我在一个控制器中有这些功能。我成功导入了数据,但无法使用$add、$remove和$edit。我使用$RootScope,因为保存的项目处于不同的状态,因此控制器也不同。我是新来的,所以我非常感谢你的帮助 angular .module("") .factory("Factory",function($http,$firebaseArray){ var ref = new Firebase('https://****.firebaseio.com/');
$add
、$remove
和$edit
。我使用$RootScope
,因为保存的项目处于不同的状态,因此控制器也不同。我是新来的,所以我非常感谢你的帮助
angular
.module("")
.factory("Factory",function($http,$firebaseArray){
var ref = new Firebase('https://****.firebaseio.com/');
return{
ref:$firebaseArray(ref)
}
});
$scope.saveItems = function() {
console.log($scope.item);
$rootScope.items.push($scope.item);
$scope.item = [];
$mdSidenav('right').close();
}
$rootScope.removeItems = function(item) {
var index = $rootScope.items.indexOf(item);
$rootScope.items.splice(index, 1);
};
$rootScope.editItems=function(item){
$rootScope.editing = true;
$mdSidenav('right').open();
$rootScope.item=item;
$rootScope.saveEdit=function(){
$rootScope.editing=false;
$mdSidenav('right').close();
};
};
Firebase中的阵列可能有点棘手。Firebase博客中有一篇文章详细介绍了一些细节。但最需要了解的是,数组实际上是作为对象存储的(这会使通过索引进行访问变得棘手),多个客户端可能同时更新一个数组,从而导致意外的结果 在你的例子中,我认为思考一下通过你的应用程序的数据流是很有帮助的。$firebaseArray的优点在于,每当该数组在Firebase上更新时,更改都会广播到所有连接的客户端 在您的应用程序中,更新Firebase上的数据并让$firebaseArray广播更改比更新$rootScope上的内容以查看视图中反映的更改更有意义。使用Firebase阵列提供的方法,您实际上可以直接在视图中执行此操作(请参阅下面的HTML部分) 并且认为:
//HTML example with remove only, can apply to add or edit
<ul>
<li ng-repeat="item in items">
{{ item.property }}
<button ng-click="items.$remove(item)">x</button>
</li>
</ul>
//仅带删除的HTML示例,可应用于添加或编辑
-
{{item.property}}
x
这里最大的变化不是在客户端更新数据,然后尝试将其同步回Firebase,而是在Firebase上更新数据,然后让$firebaseArray将更改同步到客户端
在您上面概述的基本CRUD操作方面,本手册有相当详细的内容
//HTML example with remove only, can apply to add or edit
<ul>
<li ng-repeat="item in items">
{{ item.property }}
<button ng-click="items.$remove(item)">x</button>
</li>
</ul>