Last active
August 29, 2015 14:25
-
-
Save deanapeterson/aa8b1a7b6907fe3f1062 to your computer and use it in GitHub Desktop.
Super simple advanced model service for Angular.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
angular | |
.module("app", []) | |
.factory("MyModel", MyModelFactory) | |
.controller("AppController", AppController); | |
function MyModelFactory($http){ // | |
var url = "/my-service"; | |
var originalData; | |
var service = { | |
data : [], //assumes data is a collection of same object | |
//CRUD Methods | |
get : getFn, | |
save : saveFn, | |
add : addFn, | |
remove : removeFn, | |
//Data Retrieval Methods | |
getById : getByIdFn, | |
getChanged : getChangedFn //for collections | |
}; | |
return service; | |
//CRUD Methods | |
function getFn(params){ | |
return $http.get(url,{ | |
params : params | |
}).then(copyOriginalData); | |
} | |
function saveFn(){ | |
return $http.post(url, service.data); | |
} | |
//after adding perform a refresh operation | |
function addFn(newItem){ | |
return $http.post(url + "/new", newItem ) | |
.then(function(){ | |
return service.get(); //get fresh list | |
}); | |
} | |
function removeFn(itemId){ | |
return $http.delete(itemId) | |
.then(function(){ | |
return service.get(); | |
}) | |
} | |
//Data retrieval methods | |
function getById(id){ | |
//search service.data array for item that matches id | |
//underscore/lodash _.findWhere() works great for this | |
} | |
function getChanged(){ | |
//run comparison between originalData and service.data | |
//return only changed. | |
} | |
//Private Methods | |
function copyOriginalData(response){ | |
originalData = angular.copy(response.data); | |
service.data = response.data; | |
return service.data; | |
} | |
} | |
//USAGE in controller | |
// | |
function AppController(MyModel){ | |
var app = this; | |
app.MyModel = MyModel; // <div ng-repeat="item in app.MyModel.data"></div> | |
activate(); | |
function activate(){ | |
app.MyModel.get(); // notice no need to directly bind return data in the controller | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment