python ruby-programming-language Smalltalk Vue.js Knockoutjs TypeScript JavaScript, OOPs JavaScript Angular 8,7,6,5,4 and 2 Interview Questions and Answers Angular 8,7,6,5,4 and 2 Interview Questions and Answers Angular 4 Angular 2 AngularJs 1.x NodeJs Perl Programming R Programming RequireJs Rust Programming Backbonejs closure programming language go-programming-language kotlin-programming-language
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

Hi there! Welcome to my blog. My name is Anil Singh. I'm a author of this blog. For more detail about me, kindly refer to this link..
My Blogs - http://code-sample.com and http://code-sample.xyz
My Books - Interview Questions and Answers Books- Get Your Book in 15+ Digital Stores Worldwide..

You Might Also Like
www.code-sample.com/. Powered by Blogger.
ASK Questions