我想对注入(inject)特定服务的每个函数运行同一行代码。例如:
app.service('sameInitService', function ($rootScope) {
this.init = function (scope) {
scope.foo = $rootScope.foo;
}
});
app.controller('oneController', function ($scope, sameInitService) {
sameInitService.init($scope); // <- This line of code
});
app.controller('twoController', function ($scope, sameInitService) {
sameInitService.init($scope); // <- Is the same
});
是否有一种 Angular 方法可以避免在注入(inject)此服务时编写同一行代码?
最佳答案
这可以通过装饰 $controller 服务来完成,但在这种情况下,所有 Controller 都将以这种方式初始化。
angular.module('App', [])
.config(['$provide', function($provide) {
$provide.decorator('$controller', [
'$delegate', 'sameInitService',
function controllerDecorator($delegate, sameInitService) {
return function(constructor, locals) {
sameInitService.init(locals.$scope);
return $delegate(constructor, locals, true);
}
}
]);
}])
参见 jsfiddle here .
关于javascript - 注入(inject) Angular 服务时运行相同的代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40402920/