Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

angularjs

I'm a huge fan of angular but it's got some tricky concepts with extremely nuanced differences between them and this is one of them.

I just want to create an class that I can use to create custom objects in my Angular controllers and factories. It surely shouldn't be that hard but I can't figure out how to do it. I want to have a custom, ResultSet class which I can instantiate to create instances of ResultSet. However for the life of me I can't figure out the correct syntax of factory v. service to use.

This is all I want:

ResultSet = function(dataSet){ 
  this.filter = function(){ 
    # filters and returns dataSet
    # ...
  }
}

and then I want to be able instantiate an instance of ResultSet inside a controller etc:

MyApp.controller('pageCtrl', ['ResultSet',  (ResultSet) ->
  # ...
  rs = ResultSet.new(dataToFilter)

How can I create a service that allows me to create instances of my custom object?

It seems more correct to use an Angular Service rather than a Factory since a service returns an instance of an object (which is exactly what I want). But I can't figure out how to do this...

How would I use a service to declare my custom ResultSet class and then how would I instantiate an instance from it?

like image 576
Peter Nixey Avatar asked Nov 11 '14 13:11

Peter Nixey


People also ask

What is Controlleras in AngularJS?

In AngularJS, a Controller is defined by a JavaScript constructor function that is used to augment the AngularJS Scope. Controllers can be attached to the DOM in different ways.

What is object in AngularJS?

In AngularJS, $scope is the application object (the owner of application variables and functions). The controller creates two properties (variables) in the scope (firstName and lastName). The ng-model directives bind the input fields to the controller properties (firstName and lastName).

What is providers in AngularJS?

A provider is an object with a $get() method. The injector calls the $get method to create a new instance of a service. The Provider can have additional methods which would allow for configuration of the provider. AngularJS uses $provide to register new providers.

What is factory method in AngularJS?

What is Factory in AngularJS? Factory is an angular function which is used to return the values. A value on demand is created by the factory, whenever a service or controller needs it. Once the value is created, it is reused for all services and controllers. We can use the factory to create a service.


2 Answers

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.

like image 116
Amrit Kahlon Avatar answered Sep 23 '22 20:09

Amrit Kahlon


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.

like image 30
JB Nizet Avatar answered Sep 25 '22 20:09

JB Nizet