Teddarific Teddarific - 3 months ago 34
AngularJS Question

Creating Custom Objects in AngularJS

I would like to implement my own custom object/classes in AngularJS. However, I'm getting stuck on the concept of using factories/services as custom objects - I understand that factories and services are there to provide the business logic of the app, but can I create multiple factories and services in an app? And if so, what exactly does the term "singleton"" (which many of the articles I've read have described services as) imply?

So for example, would this be the valid and/or the preferred way to go about creating a basic school object populated with student objects in AngularJS?

var school = {};
school.students = [];
school.addStudent = function(){
var newStudent = new student();
return school;
//anyway to toss in a constructor here?
this.name = 'name';
this.getName = function(){
return this.name;
schoolService.addStudent(); //obviously normally wouldn't do this, but for demonstration purposes
$scope.students = schoolService.students;
//expect $scope.students to equal an array of length 1, with one student object

Thanks in advance, and sorry for all the nested questions!

Rob Rob

Singletons stay static. Controllers are loaded as they're called. You can store the students in the service as it will persist through the life of your application and can be shared between controllers.



function AppCtrl($scope, SchoolService) {
  $scope.students = SchoolService.students;
  $scope.addStudent = function() {
    $scope.newStudent = {};

function SchoolService() {
  var service = {
    students: []
  return service;


<div ng-app="myApp" ng-controller="AppCtrl">
  <form ng-submit="addStudent()">
    <input type="text" ng-model="newStudent.first">
    <input type="text" ng-model="newStudent.last">
    <button type="submit">
      Add New Student
    <li ng-repeat="student in students"> {{ student.first}} {{ student.last }} </li>