Enter $ log in each controller and service

Is there a way to inject AngularJS $ log into each service and controller? It just feels a little redundant, specifying it for everyone.

+6
source share
3 answers

Another way you could do this is to add a method to rootScope and then access it via $ scope. $ root in the controllers, thereby avoiding another injection. I do not know how bad this is, how global.

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> 
+2
source

Injection 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 would not do that.

+1
source

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

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

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

 angular.module('myModule') .controller('MyController', MyController); MyController.$inject = []; // <-- see, no $log required! function MyController() { angular.log.info("Hello world"); } 

You can even take it one step further and add angular.info = $ log.info if you want to shorten it a bit.

0
source

All Articles