AngularJS控制器内部工厂的不同依赖注入
假设我有多个工厂,这些工厂内部具有相同的功能和变量。例如,
var app = angular.module('app', []);
app.factory('employerFactory', function () {
return {
firstName: 'Kristoffer',
lastName: 'Karlsson',
};
});
app.factory('employeeFactory', function () {
return {
firstName: 'Alice',
lastName: 'Guo',
};
});
现在我有了这样的控制器:
app.controller('MyController', function($scope, myFactory) {
$scope.firstName = myFactory.firstName;
$scope.lastName = myFactory.lastName;
});
我的问题是如何启动两个控制器,一个是在雇主中通过依赖性,另一个是雇员。我知道RouterProvider可以帮助将不同的控制器路由不同的URL路由。我可以操纵它以将不同的工厂传递到控制器中吗?类似
$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'
});
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'
});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
只需将服务用作额外的层来处理交换逻辑,在其中注入两个工厂,然后创建方法来处理共同功能:
最后将其注入控制器,并调用其方法,然后
根据您想要的任何方法, ,这只是它如何工作的一个例子。
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.