Search code examples
angularjsangularjs-material

angular-material, how to add a new service?


how to add a new service to module ?

in angularjs, can be achieved like this:

var app = angular.module('myApp', []);
app.controller('myController', function(){
    app.service('userService', function(){
        // .....
    });
    var service = angular.injector(['ng', 'myApp']).get('userService');
    // ......
});

but in angular-material, this will thow an exception.

Error: [$injector:unpr] Unknown provider: $rootElementProvider <- $rootElement <- $$animateQueue <- $animate <- $compile <- $mdUtil <- $mdTheming <- $$animateQueue

Codepen: enter link description here


Solution

  • You can do something like this. You can inject your service into controller and use all the methods and properties of your service.

    var app = angular.module('myApp', []);
    app.service('userService', function(){
            // .....
        });
    app.controller('myController', function(userService){
    
        // ......
    });
    

    Codepen: https://codepen.io/anon/pen/owOaeN

    For more Info: https://docs.angularjs.org/guide/di