Answer the question
In order to leave comments, you need to log in
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');
}]
}
}])
Answer the question
In order to leave comments, you need to log in
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');
}
};
});
который должен (по документации) создавать свой экземпляр конструктора:
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question