Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 412
Brian F Avatar asked Apr 09 '14 02:04

Brian F


People also ask

When you inject a service into a controller?

When a service or controller needs a value injected from the factory, it creates the value on demand. It normally uses a factory function to calculate and return the value. Let's take an example that defines a factory on a module, and a controller which gets the factory created value injected: var myModule = angular.

Can $scope be injected while creating service?

Explanation: No, the '$scope' cannot be injected while creating service using 'factory' method.

What are the objects components can be injected into AngularJS?

In Angular. JS, dependencies are injected by using an “injectable factory method” or “constructor function”. These components can be injected with “service” and “value” components as dependencies.

How AngularJS Dependency Injection works?

Dependency Injection is a software design in which components are given their dependencies instead of hard coding them within the component. It relieves a component from locating the dependency and makes dependencies configurable.


1 Answers

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>
like image 67
Narayana Avatar answered Oct 14 '22 10:10

Narayana