1

I have a native JavaScript class:

var Holder = new function(elements) {

    this.elements = elements;

    this.anyFunction() {
        // use of this.elements
    };

};

How to use it in an Angular-way? For example, if I would like to use:

.controller('AnyController', ['Holder',
function (Holder) {

    var elements = [
        {id: 1, label: 'foo'},
        {id: 2, label: 'bar'}
    ];

    $scope.holder = new Holder(elements);

}])

How should I register my Holder class then? What are the options (if any)?

In parallel, is it that bad to use native JavaScript classes in an Angular app (i.e. without integrating it within the framework)?

3
  • Why not create it as a service? The .service method can take a class. Check out tutorials on how to do it with Coffeescript where they uses classes, then look at the compiled JavaScript. Commented Jan 30, 2014 at 8:46
  • @elclanrs If I understood services correctly, all Angular services are application singletons (see AngularJS: Creating Services, last section: "Services as singletons"), while I need a new instance each time it is injected in a parameter. Am I wrong? Commented Jan 30, 2014 at 8:50
  • As I understand it, a factory is a singleton, but a factory can generate a class that can create instances. So the factory would return a reference to the constructor when you inject it, or a function that calls the constructor (without using new). But I don't know what's good practice on this TBH. Commented Jan 30, 2014 at 8:57

2 Answers 2

3

You could return a class with a factory

    .factory('Holder', function() {
        return (function (){
            this.foo = foo;
            this.bar = bar;
        });
    });

Now to use it

.controller('AnyController', ['Holder', function (Holder) {
    var holder = new Holder();
}]);

EDIT Use a factory instead of a service, as suggested in the comments

Sign up to request clarification or add additional context in comments.

1 Comment

then call it factory, if you need new instances each time :)
0

As I understand it, a factory is a singleton, but a factory can generate a class that can create instances. So the factory would return a reference to the constructor when you inject it, or a wrapper function around the constructor to use it without using new:

.factory('Holder', function() {
  function Holder(elements) {
    this.elements = elements; 
  }
  Holder.prototype.get = function() {
    return this.elements;
  };
  return function(elements) {
    return new Holder(elements);
  };
})

.controller('Main', function($scope, Holder) {
  var elements = [
    {id: 1, label: 'foo'},
    {id: 2, label: 'bar'}
  ];
  $scope.elements = Holder(elements).get();
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.