“Models” and “Collections” in Ionic and Angular

posted in: Uncategorized | 0

Original Question: “I want to create a collection or model in a project Angular Ionic (like Backbonejs). Is it possible? If yes, can I use Backbone? If no, what can I do (the best way)? Thanks.”

tl;dr Answer

Model = Object
Collection = Array of Object

Long Answer

Typically in Angular, you would just use straight up vanilla JavaScript objects.

var person = {
   firstName: "Andrew",
   lastName: "McGivery"
}

And a collection would just be an array of these objects…

var person1 = {
   firstName: "Andrew",
   lastName: "McGivery"
}

var person2 = {
   firstName: "Léon",
   lastName: "Jiresse"
}

var people = [person1,person2];
//or
people = [];
people.push(person1,person2);

In a way, the architecture of Angular kind of assumes you are getting your models from the backend (a server, webservice, etc) via $http.

app.factory("PeopleService",function(){
   return {
     GetPeople: function(){
        return $http.get('path/to/backend/people');
     }
   }
}

app.controller("PeopleController",function($scope,PeopleService){
    PeopleService.GetPeople().then(function(people){
        $scope.people = people;
    });
});

However, this assumed that the response from the service is a JSON-like response, ready to be binded as is:

<div ng-repeat="person in people">
 Person: {{person.firstName}} {{person.lastName}}<br />
</div>

This may not always be the case, which is where you would do some processing of the response before fully resolving the promise:

app.factory("PeopleService",function(){
   return {
     GetPeople: function(){
        return $http.get('path/to/backend/people').then(function(response){
			//Process Response, example convert XML to javascript objects
			return response;
		});
     }
   }
}

More Reading

Ionic: Using Factories and Web Services for Dynamic Data
The Stack Overflow Question
Models and Services in Angular
What is a collection? (Backbone Tutorials)

My name is Andrew McGivery. I currently work full time as an application developer at Manulife Financial in Canada. My current passion is building and leading highly engaged teams where employee happiness, learning, and growth is a priority.

Leave a Reply