Join the Stack Overflow Community
Stack Overflow is a community of 4.7 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

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?

app.factory('schoolService',function(student){
    var school = {};
    school.students = [];
    school.addStudent = function(){
         var newStudent = new student();
         this.students.push(newStudent);
    }
    return school;
}
app.service('student',function(){
     //anyway to toss in a constructor here?
     this.name = 'name';
     this.getName = function(){
         return this.name;
     }
}
app.controller('schoolCtrl',function(schoolService){
     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!

share|improve this question
up vote 0 down vote accepted

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.

https://jsfiddle.net/jtgd6tjn/

Angular

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

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

HTML

<div ng-app="myApp" ng-controller="AppCtrl">
  <form ng-submit="addStudent()">
    <input type="text" ng-model="newStudent.first">
    <br>
    <input type="text" ng-model="newStudent.last">
    <br>
    <button type="submit">
      Add New Student
    </button>
  </form>
  <hr>
  <ul>
    <li ng-repeat="student in students"> {{ student.first}} {{ student.last }} </li>
  </ul>
</div>
share|improve this answer
    
Thanks for the response Rob, but where would I define the student object, and how would I inject it into the service? Would it be as simple as defining a var with the student object, and using function SchoolService(student)? Thanks! – Ted Aug 9 at 15:13
    
Are you talking about the newStudent? – Rob Aug 9 at 15:15
    
Kind of - Ideally I would like to make student a class that has its own functions,data etc to avoid cluttering the factory. So $scope.students and SchoolService.students, for example, would be an array of student objects from a student class. I understand that your example would work for this purpose, but the app I'm currently working on is much more complex and there is a lot of calculations and data I need to store that isn't directly coming from user input. – Ted Aug 9 at 15:26
    
Well, services are designed for functionality regarding anything related to students. You can make it as complex as you'd like or create smaller factories and inject them into other factories and controllers as needed. Honestly, I've never worked with classes perse in Angular and just relied on services and have had no problems. You might need to dig a bit deeper online on using classes within Angular. Granted this url is a style guide, but it does outline pretty well the responsibility of structuring Angular apps: github.com/johnpapa/angular-styleguide/blob/master/a1/README‌​.md – Rob Aug 9 at 15:35
    
Ok great, thanks for the explanation! – Ted Aug 9 at 15:47

Services/Factories as you mentioned are used as logic containers. They can be created once and injected into multiple controllers to carry out the business logic. This helps in the code reusability and logic abstraction.

'Singleton' is the right way to define what services are. they are initialized once while the application is being bootstrapped. In general terms, you could use service as 'getter and setter'. If you are familiar with coding, you must know what it means.

And, no as far as your example is mentioned services are not used for creating objects like the way you want it. For creating a new object in Javascript you can follow the below approach

var Student = function(name){
   this.name = name;
};

var roy = new Student('Roy');

Hope this answers your questions. You can read more about service/factories in this Blog

share|improve this answer
    
Thanks for the response Akhil! So the object I intend on creating is quite sizable, and would ideally like to write it ouside of my factory. Would I simply define the object outside of the app, and pass it in as a dependency? Thanks! – Ted Aug 9 at 15:11

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.