How to inject services into AngularJs controllers?

How to inject services into AngularJs controllers?

Hello everyone, Today's I faced an issues regarding calling one controller methods in other controller or we can say the inject services into controllers. Now I solved this issues and going to share in detail.

The example detail about injecting services into controllers as give below.

var app = angular.module("injectServicesApp", ['']);

//This is factory
app.factory('injectServicesFactory', function () {
    return {
        myFactoryMethod: function () {
            alert("inject my Services Factory Method");
    }
    };

//This is controller 2
app.controller('injectServicesCtrl1', function ($scope, injectServicesFactory) {
    $scope.method1 = injectServicesFactory.myFactoryMethod();
});

//This is controller 2
app.controller('injectServicesCtrl2', function ($scope, injectServicesFactory) {
    $scope.method2 = injectServicesFactory.myFactoryMethod();
});

In other ways we can handle to injecting services into controllers as give below.

//Conroller 1
app.controller('injectServicesCtrl1', function ($scope) {
    this.myMethods = function () {
        alert("My Ctrl1 method call!");
    }
});

//Conroller 2
app.controller('injectServicesCtrl2', function ($scope, $controller) {
    var ctrl1 = $controller('injectServicesCtrl1');
    ctrl1.myMethods();
});


Thank you!
ANIL SINGH

Anil Singh is an author, tech blogger, and software programmer. Book writing, tech blogging is something do extra and Anil love doing it. For more detail, kindly refer to this link..
My Blogs - https://code-sample.com and https://code-sample.xyz
My Book1 - BEST SELLING ANGULAR BOOK (INCLUDING ALL VERSIONS 2, 4, 5, 6, 7)
My Book2 - ANGULAR 2 INTERVIEW QUESTIONS BOOK - Both Books are Available on WorldWide.

www.code-sample.com/. Powered by Blogger.