mercredi 24 décembre 2014

AngularJS Service Creation Design Pattern

I feel like I am missing a big concept when working with AngularJS. I am very new to it and web development in general. I am creating my first SPA. The SPA has about 10 or so pages to it. Each page will capture information from the user. So, I setup my module, my controllers, my directives, and my routes. To this point, AngularJS was fun, and easy to follow. Now, I have to persist my model between my views. I have to create a custom service or factory. My experience with creating a service feels utterly contrary to what I have experienced so far. The service is/has the potential to be massive. For each property I make, I then create a get/set function with validation where necessary. This feels wrong to me... If I had 50 input elements that I need to persist, this just doesn't seem optimal to me.



app.service('myService', ['$log'], function($log){
var self = this;
var globalMessage = "";
var businessName = "";
this.getBusinessName = function() { return businessName; }
this.setBusinessName = function (name) {
if (name) {
businessName = name;
$log.info("Business Name Set");
self.globalMessage = "";
return self.getBusinessName();
}
else {
self.globalMessage = "Error, invalid business name";
$log.warn("Error");
return self.globalMessage;
}
}
})


Then I wire these properties with my controller



app.controller('step01Controller', function ($scope, myService) {
$scope.$watch(function () { return myService.globalMessage }, function (newVal, oldVal) {
if (typeof newVal !== 'undefined') {
$scope.globalMessage = myService.globalMessage;
}});
$scope.$watch('BusinessName', function (x) { myService.setBusinessName(x) });
});


Is there a better paradigm or design that I can implement that isn't so 'verbose' in developing? Thanks! I am also new to SO. Please forgive my noobness.


Aucun commentaire:

Enregistrer un commentaire