Brian F
Brian F

Reputation: 1660

Inject $log into every controller and service

Is there any way to inject AngularJS's $log into every service and controller? It just feels a little redundant specifying it for every one.

Upvotes: 6

Views: 1302

Answers (3)

Robin Sving
Robin Sving

Reputation: 3330

Here's a solution for those who think that using the $rootscope requires too much fuss: add the $log to the angular object.

angular.module('myModule')
    .run(['$log', function($log) {
        angular.log = $log;
    }]);

Then when you create your controllers, no $log is required.

angular.module('myModule')
     .controller('MyController', MyController);

MyController.$inject = []; // <-- see, no $log required!

function MyController() {
    angular.log.info("Hello world");
}

You could even take it a step further and add angular.info = $log.info if you wish to shorten it a bit more.

Upvotes: 0

Narayana
Narayana

Reputation: 2744

Another way you could do it is to add a method to the rootScope, and then access it through $scope.$root in your controllers, thus avoiding another injection. I don't know if it is as bad as 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>

Upvotes: 2

Pieter Herroelen
Pieter Herroelen

Reputation: 6066

Injecting it seems impossible to me without defining it in the function parameters. But you can make it available:

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

Another way would be to set it as a global variable (window.$log), but I wouldn't do that.

Upvotes: 1

Related Questions