Reputation: 4162
I have a TypeScript class like this:
personName
is a custom filter which cannot be used on view/template in this exampleCode:
export class Person {
private $filter;
private name: string;
private sureName: string;
constructor($filter: ng.IFilterService, name: string, sureName: string) {
this.$filter = $filter;
this.name = name;
this.sureName = sureName;
}
public getName(): string {
return this.$filter('personName')(this.name, this.sureName);
}
}
This can be used in controller like this:
export class PeopleController {
private $filter: ng.IFilterService;
private person1 = new Person(this.$filter, 'Joe', 'Smith');
private person2 = new Person(this.$filter, 'John', 'Doe');
// ...
// private person100 = new Person(this.$filter, ...)
constructor($filter: ng.IFilterService) {
this.$filter = $filter;
}
}
angular.module('myApp').controller('PeopleController', PeopleController);
Is it possible to rewrite Person
class to can be inited without the $filter
? In other words, can I write Person
class as Angular factory with dependency injection, then inject this factory into controller and make instances?
I'd like to have something like this:
export class PeopleController {
private PersonFactory: Person;
private person1 = new PersonFactory('Joe', 'Smith');
private person2 = new PersonFactory('John', 'Doe');
// ...
// private person100 = new Person(...)
constructor(PersonFactory: Person) {
this.PersonFactory = PersonFactory;
}
}
angular.module('myApp').factory('PeopleFactory', People);
angular.module('myApp').controller('PeopleController', PeopleController);
Upvotes: 0
Views: 155
Reputation: 31600
You can make a factory that injects the $filter service and returns a function that takes the rest of the parameters and returns a Person.
It would look something like this.
interface PersonFactory {
(name: string, surname: string): Person
}
angular.module('mymodule').factory('PersonFactory', function($filter: ng.IFilterService): PersonFactory {
return function(name: string, surname: string): Person {
return new Person($filter, name, surname);
}
});
You will be able to use it like this:
angular.module('myModule').controller('SomeCtrl', function(PersonFactory: PersonFactory) {
let p = PersonFactory('John', 'Smith');
});
Upvotes: 1