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

Hey! I'm Anil Singh. I author this blog. I'm Active Blogger, Programmer. I love learning new technologies, programming, blogging and participating the forum discussions more...
My Blogs - http://www.code-sample.com and http://www.code-sample.xyz
My Books - Google Amazon and Flipkart Book Store!

You Might Also Like
Post a Comment
www.code-sample.com/. Powered by Blogger.
ASK Questions
SQL Server NodeJs TypeScript JavaScript Angular SQL Server My Book