Note that there are some explanatory texts on larger screens.

plurals
  1. POAngularJS data usage pattern
    text
    copied!<p>I am new to angularjs and in my application I am making a REST API call and the returned response is stored as a model object. For my view, I have created a seperate view model object since the response from the API cannot be as such used in the UI.</p> <p>Is this a right approach? Note that I am using two different models -> One gets data from the server and other is used as UI backing model. This is similar to a backing bean and DAO objects in Java frameworks.</p> <p>Please advise whether this approach is fine or should it be changed. If so how?</p> <p><strong>Update</strong> Have illustrated the issue in <a href="http://jsfiddle.net/LGEKX/" rel="nofollow">http://jsfiddle.net/LGEKX/</a></p> <pre><code>function mycontroller($scope){ //The view model is populated by a seperate method var viewmodel = populateViewModel(); $scope.viewmodel = viewmodel; } function populateViewModel(){ //Call service to update local model var backendModel = serviceCall(); //Invoke conversion service var converteModel = convertBackEndModel(backendModel); } function serviceCall(){ //Service method calls server side API and the data returned is returned in success callback $http({method: 'GET', url: '/someUrl'}). success(function(data, status, headers, config) { return data; }). error(function(data, status, headers, config) { ... }); } function convertBackEndModel(data){ //This takes the data returned from API call as input and creates a view model //which will be used for angularjs view (in HTML) var viewModel = {}; viewModel.name = backendModel.backendName; //Though this is simple, actual code has lots of logic which basically converts one JSON structure to another } </code></pre> <p>and in my HTML</p> <pre><code>&lt;div ng-app&gt; &lt;div ng-controller="mycontroller"&gt; &lt;!-- Binding to viewmodel from the HTML--&gt; &lt;div ng-model="viewmodel.name"&gt;&lt;/div&gt; &lt;/div&gt; </code></pre> <p></p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload