Integrating native JavaScript classes in an Angular app

后端 未结 2 509
借酒劲吻你
借酒劲吻你 2021-01-16 08:50

I have a native JavaScript class:

var Holder = new function(elements) {

    this.elements = elements;

    this.any         


        
2条回答
  •  无人及你
    2021-01-16 09:25

    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();
    });
    

提交回复
热议问题