Say I have multiple factories and these factories have same functions and variables inside. For example,
var app = angular.module('app', []);
app.factory('employerFactory', function () {
return {
firstName: 'Kristoffer',
lastName: 'Karlsson',
};
});
app.factory('employeeFactory', function () {
return {
firstName: 'Alice',
lastName: 'Guo',
};
});
Now I have a controller like this:
app.controller('MyController', function($scope, myFactory) {
$scope.firstName = myFactory.firstName;
$scope.lastName = myFactory.lastName;
});
My question is that how to initiate two controllers, one is passed in employerFactory as dependency and the other is employeeFactory. I know a routerProvider could help to route different controllers for different url. Can I manipulate on it to pass different factories into controller? something like
$routeProvider.
when('/a', {
templateUrl: 'test.html',
controller: 'MyController' // should get passed factory 'employerFactory'
}).
when('/b', {
templateUrl: 'test.html',
controller: 'MyController' // should get passed factory 'employeeFactory'
});
Just use a service as an extra layer to deal with the switching logic, inject both factories in it, then create methods to handle common functionality:
Finally inject it into your controller, and call its methods
The switching logic can be based on whatever you want, this is just an example of how it could work.