Peter Nixey Peter Nixey - 6 months ago 29
AngularJS Question

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

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?

Answer
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('ResultSet', function() {
    ResultSetClass = function ResultSetInstance(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.

Comments