我有一个带有一系列对象的Angularjs项目。仅支持常绿浏览器。
工厂
var _data = [];
var _myObject = {};
var _objectsModified = [];
function loadData(){
$http.get("data.json").success(function(response){
_data = response.data;//[{id: 1, title: "foo"},{id: 2, title: "bar"}]
_data.forEach(function(e,i){
_myObject[e.id] = i;
});
});
}
function getData(){
return _data;
}
function getObjectById(id){
return _data[_myObject[id]];
}
function storeObjectById(object){
_data[_myObject[object.id]] = object;
_objectsModified.push(object);
}
function saveModifications(){
$http.put("save_endpoint", _objectsModified).success(function(response){
if(response.success) _objectsModified = [];
});
}
控制器
var objectCopy = angular.copy(getObjectById(1));
// user makes changes to the object
// store object
storeObjectById(objectCopy);
Controller正在创建一个对象的角度副本,对其进行编辑然后将其放回到数组中。
这是一种有效的方法吗?
编辑
工厂
var _data = [];
var _objectsModified = [];
var _editObjectRef = {};
function loadData(){
$http.get("data.json").success(function(response){
_data = response.data;//[{id: 1, title: "foo"},{id: 2, title: "bar"}]
});
}
function getData(){
return _data;
}
function getCopyOfObject(object){
_editObjectRef = object;
return angular.copy(_editObjectRef);
}
function storeModifiedObject(object){
angular.extend(_editObjectRef, object);
_objectsModified.push(object);
}
function saveModifications(){
$http.put("save_endpoint", _objectsModified).success(function(response){
if(response.success) _objectsModified = [];
});
}
控制器
$scope.data = Factory.loadData();
$scope.editObject = function(object){
$scope.editObjectCopy = Factory.getCopyOfObject(object);
}
$scope.storeModifiedObject = function(object){
Factory.storeModifiedObject(object);
}
HTML
<a href="javascript:void(0)" ng-repeat="object in data" ng-click="editObject(object)">{{object.title}}</a>