How do I create a custom object class that's available to my methods in AngularJS

Maybe you were looking for something like this:

.factory('User', function (Organisation) {

  /**
   * Constructor, with class name
   */
  function User(firstName, lastName, role, organisation) {
    // Public properties, assigned to the instance ('this')
    this.firstName = firstName;
    this.lastName = lastName;
    this.role = role;
    this.organisation = organisation;
  }

  /**
   * Public method, assigned to prototype
   */
  User.prototype.getFullName = function () {
    return this.firstName + ' ' + this.lastName;
  };

  /**
   * Private property
   */
  var possibleRoles = ['admin', 'editor', 'guest'];

  /**
   * Private function
   */
  function checkRole(role) {
    return possibleRoles.indexOf(role) !== -1;
  }    

  /**
   * Static property
   * Using copy to prevent modifications to private property
   */
  User.possibleRoles = angular.copy(possibleRoles);

  /**
   * Static method, assigned to class
   * Instance ('this') is not available in static context
   */
  User.build = function (data) {
    if (!checkRole(data.role)) {
      return;
    }
    return new User(
      data.first_name,
      data.last_name,
      data.role,
      Organisation.build(data.organisation) // another model
    );
  };

  /**
   * Return the constructor function
   */
  return User;
})

From this post by Gert Hengeveld.


myApp.factory('ResulSet', function() {
    function ResultSetInstance(dataSet) { 
        this.filter = function(){ 
            // ...
        }
    }

    return {
        createNew: function(dataSet) {
            return new ResultSetInstance(dataSet);
        }
    };
});

and then

myApp.controller('pageCtrl', function(ResultSet) {
    var someData = ...;
    var rs = ResultSet.createNew(someData);
}

Edit (from the question asker)

On experimenting with this further I found that you didn't even need to have the createNew method.

myApp.factory('ResultSetClass', function() {
    ResultSetClass = function(dataSet) { 
        this.filter = function(){ 
            // ...
        }
    }

    return ResultSetClass
});

works just fine and then you can call new ResultSetClass(args).

Note for those using Coffeescript

Coffeescript will return the last variable or method in your class instance so if you are using coffeescript (as a general rule), it's imperative to return this at the end of the class definition

myApp.factory 'ResultSetClass', () ->
  ResultSetClass = (dataset) ->
    this.filter = () ->
      # do some stuff
    return this

  return ResultSetClass

If you don't return this explicitly then you'll find that when you call

myApp.factory 'ResultSetClass', () ->
  ResultSetClass = (dataset) ->
    this.filter = () ->
      # do some stuff

then you'll simply be left with the last thing the coffeescript returns which is the filter method.

Tags:

Angularjs