【发布时间】:2014-04-09 02:34:25
【问题描述】:
有没有办法将 AngularJS 的 $log 注入到每个服务和控制器中?为每个人指定它只是感觉有点多余。
【问题讨论】:
有没有办法将 AngularJS 的 $log 注入到每个服务和控制器中?为每个人指定它只是感觉有点多余。
【问题讨论】:
另一种方法是向 rootScope 添加一个方法,然后通过控制器中的 $scope.$root 访问它,从而避免再次注入。不知道是不是和globals一样糟糕。
testapp.js
(function(){
'use strict';
angular.module('app', [])
.run(function($rootScope, $log) {
$rootScope.log = function(msg){
$log.info(msg);
}
})
.controller('LogCtrl', ['$scope', function LogCtrl($scope) {
$scope.logThis = function(msg){
$scope.$root.log(msg);
};
}]);
})();
test.html
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.0-beta.5/angular.min.js"></script>
<script src="testapp.js"></script>
</head>
<body ng-app="app">
<div ng-controller="LogCtrl">
<p>Enter text and press the log button.</p>
Message:
<input type="text" ng-model="message"/>
<button ng-click="logThis(message)">log</button>
</div>
</body>
</html>
【讨论】:
$log 而不是必须输入 $scope.$root.log 同时在我以前没有的地方注入 $scope(例如:隔离范围指令) ...我会通过
如果不在函数参数中定义它,我似乎不可能注入它。但是你可以让它可用:
var $log;
app.run(['$log',function(logService) {
$log = logService;
}]);
app.controller('MainCtrl', function($scope, myService) {
$log.warn('Controlling');
});
app.service('myService', function() {
$log.warn('Ha!');
return {};
});
http://plnkr.co/edit/Zwnay7dcMairPGT0btmC?p=preview
另一种方法是将其设置为全局变量 (window.$log),但我不会这样做。
【讨论】:
var $log 时,您基本上是在设置 window.$log
对于那些认为使用 $rootscope 需要大惊小怪的人来说,这里有一个解决方案:将 $log 添加到 angular 对象中。
angular.module('myModule')
.run(['$log', function($log) {
angular.log = $log;
}]);
然后,当您创建控制器时,不需要 $log。
angular.module('myModule')
.controller('MyController', MyController);
MyController.$inject = []; // <-- see, no $log required!
function MyController() {
angular.log.info("Hello world");
}
如果您希望进一步缩短它,您甚至可以更进一步,添加 angular.info = $log.info。
【讨论】: