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?

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!

Rob Rob
Answer

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>
Comments