0

I'm just wondering what is the best practice to view model data from server in Angular app?

For example in my controller i'm getting model from server (with custom ngResource service) and then I need to create somekind different model in my app's clientside:

customApiService.query({ url: 'items' }, function (res) {
   // made it like this and do everything in partials with "ng-repeat"?!
   $scope.items = res;

   // but i need to model server data on client...
   angular.forEach(res, function (key, i) {
     $scope.viewModel = {
        description: key.anotherNameField // e.g. different third-party services return description under different names
     };
   });
});

1 Answer 1

2

What we do is such a case is not to use the angular resource directly within controller. We create our own service

appRoot.factory('modelService', ['$resource', '$q', function ($resource, $q) {
function ModelClass() {
   this.PropertyOne=null;
   this.PropertyTwo=null; 
}
var serviceObj= {
      getData: function () {
         $resource('url').query(function(data) {
               var modelList=[];
               //Do a foreach on each record in 'data' and create 'ModelClass' object and map properties
               return modelList;
         });
      }
   }
  return serviceObj;
}]);

This allows us more control over what gets exposed to the Controller and hence the View. The ownership of the model here is with the service.

Since the same service can be injected everywhere, we do not have to custom mapping again and again.

Sign up to request clarification or add additional context in comments.

2 Comments

@Chandermani do you still recommend to write a mapping layer like above to convert server side data models to view-model and vice-versa?
We regularly use it, and it allows us great flexibility, to handle complex UI

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.