D
D
Dmitry Shvalyov2015-09-15 20:11:21
JavaScript
Dmitry Shvalyov, 2015-09-15 20:11:21

How to create a new instance of the Service (Service) when the directive is initialized?

Sat down on the problem: I have several instances of the directive, when the directive is initialized, a service is injected into its controller, which should (according to the documentation) create its own instance of the constructor:

<div sample=""></div>
<div sample=""></div>
<div sample=""></div>

angular.module('application', [])
  .service('fooBar', [function() {
    var param = null;

        this.setParam = function(value) {
            param = value;
        };

        this.getParam = function() {
            return param;
        };
  }])

  .directive('sample', [function() {
        return {
            restrict: 'AE',
            scope: false,
            controller: ['fooBar', function(fooBar) {
                console.log(fooBar.getParam());
                fooBar.setParam('test');
            }]
        }
    }])

jsfiddle.net/dmitry_shvalyov/7d7syjtx
Result in console. In theory, if the service creates a new instance (new Constructor), then each time after creation, the getParam method should return null. But something is going wrong and I don't know how to fix it.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
Mikhail Osher, 2015-09-15
@dshster

Of course, you need a factory.

angular.module('applicaton', [])

.factory('fooBar', function() {
  function Service() {
    var param = null;
    
    this.setParam = function(param) {
      param = param;
    };
    
    this.getParam = function() {
      return param;
    };
  }
  
  return function() {
    return new Service();
  }
})

.directive('sample', function() {
  return {
    restrict: 'AE',
    scope: false,
    controller: function(fooBar) {
      var service = fooBar();
      service.setParam('test');
    }
  };
});

Сергей Протько, 2015-09-15
@Fesor

который должен (по документации) создавать свой экземпляр конструктора:

вы не дочитали документацию. $injector делает это ровно один раз, вы можете его попросить сделать это еще раз, но если у вас возникает такая нужда значит вы что-то делаете не так. В целом все сервисы в ангуляре инстанцируются в единственном экземпляре.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question