I came across a problem that should be general and obvious, but I cannot circle it.
I am working on a small prototype application. My third-party developer provides me with profile data in a JSON object. Let's say it looks like this:
profile = {Name: 'John', Email: ' john@mail.com ', DOB: '1980-11-03'}
I need these values ββin several places, and I also don't want to put backend http calls into controllers, so I created a service to handle this:
angular.module('app', []) .service('ProfileService', ['$http', function ($http) { var service = this; service.Name = null; service.Email = null; service.DOB = null; service.getProfile = function () { return $http.get('/profile').then(function (response) { service.Name = response.data.Name; service.Email = response.data.Email; service.DOB = response.data.DOB; return true; }); }; return service; }]) .controller('ProfileCtr', ['ProfileService', function (service) { var vm = this; service.getProfile().then(function () { vm.Name = service.Name; vm.Email = service.Email; vm.DOB = service.DOB; }); }]);
There are a number of problems with this solution:
- Since profile data consists of primitives, direct binding to service properties will not allow automatic data synchronization.
- More importantly, it breaks down the DRY concept , as I wrote data declarations in at least 3 different places (database schema in getProfile () and in the controller).
One solution would be to add an indirect layer and create an object inside the service:
angular.module('app', []) .service('ProfileService', ['$http', function ($http) { var service = this; service.profile = {}; service.getProfile = function () { return $http.get('/profile').then(function (response) { for (key in response.data) { service.profile[key] = response.data[key]; }; return true; }); }; return service; }]) .controller('ProfileCtr', ['ProfileService', function (service) { var vm = this; service.getProfile().then(function () { vm.profile = service.profile; }); }]);
This works in general, but now I get the awkward controllerAs syntax:
<div ng-controller="ProfileCtr as ctr"> <h1> {{ ctr.profile.Name }}</h1> <p> Email: {{ ctr.profile.Email }} <br /> DOB: {{ ctr.profile.DOB }}</p> </div>
I am wondering if there is a way that gives me both: pure HTML syntax {{ ctr.Name }} and a stylish programming style.
Thanks for any tips!