AngularJS model best practice - angularjs

I have been looking at this document:
understanding-service-types
Because I am new to AngularJS I am having some problems understanding everything in there. I still don't understand the difference between a factory and a service, but I will leave that for another day.
The problem I have now, is that I created a model as a factory and now I think I may have done it wrong.
Here is my model:
commonModule.factory('optionsModel', function () {
var _options = angular.fromJson(sessionStorage.siteOptions);
var _defaults = {
rotateBackground: false,
enableMetro: true
};
if (_options) {
_defaults.rotateBackground = _options.rotateBackground;
_defaults.enableMetro = _options.enableMetro;
}
var _save = function (options) {
console.log(options);
sessionStorage.siteOptions = angular.toJson(options);
}
return {
options: _defaults,
save: _save
};
});
As you can see here, what I am doing is setting the defaults and then I check to see if we have anything in our session, if we do I then overwrite our options with the new settings.
I also have a save function which is used to save the options to the session.
Is this the best way to make this model or should I be doing it another way?

I don't think you should think about a model in the way you're doing it.
For your purpose, you can do it in a more "angular" way :
commonModule.factory('optionsModel', function () {
var factory = {
getOptions: getOptions,
saveOptions: saveOptions
}
// If you need default values, you can assign those here,
// but you can also think about adding a dependency into your factory,
// that would be bound to your default settings.
return factory;
function getOptions(){
return angular.fromJson(sessionStorage.siteOptions);
}
function saveOptions(options){
sessionStorage.siteOptions = angular.toJson(options)
}
});

Related

AngularJS - Initialize form data based on value

I am trying to add edit functionality to my app. In one view, I have a button that brings you to the edit page.
<button ng-click="editMission(selectedMission.key)">Edit Mission</button>
The value selectedMission.key is used to determine what to initialize the edit page's form data with.
In the controller the function looks like this:
$scope.editMission = function(key){
$location.path('/edit');
}
On the edit page I have:
<div data-ng-init="editInit()">
And in my controller I have:
$scope.editInit = function(){
var query = myDataRef.orderByKey();
query.on("child_added", function(missionSnapshot){
if (missionSnapshot.key()==key){
...
}
});
}
How can I run the initialize function based on the key value from editMission. Should I use some getter/setter approach with a global key variable? I tried just placing the editInit code in editMission but the form data does not populate on view load.
Common practice is to use a service to share variables between views/controllers.
So in your case you would use the getter/setter approach as you suspected. I don't know what exactly you're trying to do, but the service in your case would look something like this:
app.factory('missionKeyService', function() {
var currentMission= {};
return {
setMissionKey: function(missionKey) {
currentMission.key = missionKey;
},
getMissionKey: function() {
return currentMission.key;
}
}
})
And in your controller1:
//include 'missionKeyService' in your controller function params
$scope.editMission = function(key) {
missionKeyService.setMissionKey(key);
$location.path('/edit');
}
And controller2:
//include 'missionKeyService' in your controller function params
$scope.editInit = function() {
var currentKey = missionKeyService.getMissionKey();
//do something with this key
...
}

Calling an Angular Factory recursively gives a circular dependency error

I have an application with multithreaded comments, and I'm trying to use an Angular factory to create objects with all the necessary functions and properties recursively, since of course, a comment can have many replies, each of which can have more replies...
Below is my factory representing a comment:
app.factory("Comment", ["commentHttpService", "Comment", function(commentHttpService, Comment) {
return function(comment) {
var self = comment;
// lots of other properties and methods here
self.children = self.children.map(function(reply) {
return new Comment(reply);
});
return self;
}
}]);
Of course, this doesn't work since I'm injecting Comment into itself.
How can I resolve this and still accomplish my original goal?
app.factory("Comment", ["commentHttpService", function(commentHttpService) {
function Comment(comment) {
var self = comment;
// lots of other properties and methods here
self.children = self.children.map(function(reply) {
return new Comment(reply);
});
}
return Comment;
}]);
Another way of achieving what you want could be creating a factory that lets yu create a Comment instance which has all its apis attached to it:
app.factory("CommentFactory", function() {
function Comment(comment) {
this.message = comment;
this.replies = [];
this.getMessage = function() {
return this.message;
}
this.addReply = function(reply) {
var replyComment = new Comment(reply);
this.replies.push(replyComment);
return replyComment;
}
this.getReplies = function() {
return replies;
}
}
return {
createComment: function(message) {
return new Comment(message);
}
}
});
Here is a small plunk:
http://plnkr.co/edit/BmfCm9?p=preview
You can create comments using factory and add replies to comments which are also instances of Comments.

Creating angular base service and sub services

I'm trying to create a general service for dynamic listing objects i angular and for different types of Objects I need slightly different methods for this service. So I thought it would be the best to have a base service and some sub-services. The problem is, that I need to initialize the base service with different Objects depending on sub-service.
So that what I got so far:
Base List-Service (shortened to the relevant)
App.factory('List', ['$q',
function (){
var List = function(Item, searchParams){
this.Item = Item;
this.searchParams = searchParams;
//....
this.nextPage();
};
//.....
List.prototype.nextPage = function () {
//.....
this.Item.find({
//.....
}.bind(this));
};
return List;
}]);
Sub-service of List-Service
App.factory('UserList', [
'User', 'List','$q',
function (User, List) {
UserList = function(){
var searchParams = {
// params Object
};
return new List(User, searchParams);
};
// extend base class:
UserList.prototype.updateUser = function(id){
//.....
}
//....
return UserList;
}]);
Currently just the UserList is loaded, but: Of course it loads every time a new instance, due the new operator when it's called, but I just want one instance. But leaving the new operator throw's an error that this.nextPage(); would be undefined function. Beside this it seems the extension function updateUser is not applied.
So what's the best practice to inherit from other service with passing arguments to parent service in angular?
I gotta work it.
changed sub service to this to inherit proper from base:
App.factory('UserList', [
'User', 'List','$q',
function (User, List) {
var UserList = function(){
var searchParams = {
//.....
};
List.call(this, User, searchParams);
};
// inherit from List service
UserList.prototype = Object.create(List.prototype);
UserList.prototype.updateUser = function(id) {
//.....
};
return UserList;
}
])
;

Backbone Model gives this.set not a function in Model.initialize

I've a model listen on the vent for a event update:TotalCost, which is triggered from (unrelated) Collection C when any model M belonging to collection C changes.
This event is coded in the initialize method as below. On receiving the event I get the following error:
TypeError: this.set is not a function
this.set({ "totalsale": value});
CostModel = Backbone.Model.extend({
defaults: {
totalSale: 0,
totalTax: 0
},
initialize: function(attrs, options) {
if(options) {
if(options.vent) {
this.vent = options.vent;
}
}
this.vent.on("update:TotalCost", function(value) {
this.set({ "totalSale": value}); **//ERROR HERE**
});
}
});
It is highly possible you've forgot to add the new keyword before your model for example you have:
var user = UserModel();
// instead of
var user = new UserModel();
Have you tried using a closure?
CostModel = Backbone.Model.extend({
defaults: {
totalSale: 0,
totalTax: 0
},
initialize: function(attrs, options) {
var self = this;
if(options) {
if(options.vent) {
this.vent = options.vent;
}
}
this.vent.on("update:TotalCost", function(value) {
self.set({ "totalSale": value});
});
}
});
Perhaps you want this to refer to current CostModel instance, to do so you need to pass this to this.vent.on call so event callback will be executed in context of model:
this.vent.on("update:TotalCost", function(value) {
this.set({ "totalSale": value});
}, this);
it may be due to 'set' works on model not on object. so you can, first convert your object in to model then try..
in example:
new Backbone.Model(your_object).set('val', var);
Another cause of this error can be if you try to create a new model without using the "new" keyword
I was getting this mysterious error when using it with Parse. I had:
Parse.User().current().escape("facebookID")
... when I should have had:
Parse.User.current().escape("facebookID")
Removed the extra () and it works fine now.
Another cause:
// render() method in view object
setInterval(this.model.showName, 3000);
// showName() method in model object
showName: function(){
console.log(this.get('name')); // this.get is not a function
}

Backbone model.destroy(): Is explicit removal from collection necessary?

I have a simple question. I am looking at a function with 2 lines of code:
deleteTask: function() {
this.parent.collection.remove(this.model);
this.model.destroy();
}
If I comment out the first line, which is supposed to remove the model from its collection, things seem to work as intended (as in, the model is removed automatically). From Backbone's website, this is the relevant discription for a model's "destroy" function:
Triggers a "destroy" event on the model, which will bubble up through any collections that contain it.
Am I safe to assume that the removal of this.parent.collection.remove(this.model); will not affect the functionality of the code in any way? This is what I think, but I wanted to make sure of it.
Thank you!
If you destroy a model, it is removed from any collections that was containing it. You can see that in the backbone source
//Internal method called every time a model in the set fires an event.
_onModelEvent: function(event, model, collection, options) {
...
if (event === 'destroy') this.remove(model, options);
So yes, I wouldn't think you would need to remove the model from your collection explicitly.
But don't trust me, test for yourself :)
deleteTask: function() {
that = this;
this.model.destroy({
success: function() {
console.log(that.parent.collection);
}
});
}
Check the console for yourself to see whether the model was removed from the collection.
The solution is to override the Backbone model destroy function. I made this on an abstract model with success and callback strategy:
Parameter "data" corresponds to the original parameter "resp".
destroy: function(successCallback, errorCallback)
{
var options = { wait: true };
var model = this;
successCallback = successCallback || function() {};
errorCallback = errorCallback || function() {};
var destroy = function()
{
model.trigger('destroy', model, model.collection, options);
};
options.success = function(data)
{
if ('SUCCESS' === data.responseCode)
{
if (options.wait || model.isNew())
destroy();
successCallback(data);
if (!model.isNew())
model.trigger('sync', model, data, options);
}
else
{
errorCallback(data);
}
};
if (this.isNew())
{
options.success();
return false;
}
var xhr = this.sync('delete', this, options);
if (!options.wait)
destroy();
return xhr;
}

Resources