Integrating native JavaScript classes in an Angular app

扶醉桌前 提交于 2019-12-01 09:52:00

问题


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)?


回答1:


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




回答2:


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


来源:https://stackoverflow.com/questions/21451468/integrating-native-javascript-classes-in-an-angular-app

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!