简体   繁体   中英

How to access a controller from another controller in AngularJs

I want to use another method from another Controller in an Angularjs Module. I have two Controller one named: Booklist Controller in bookApp Module. and another one named ShowEachBook . In Booklist Controller I create ViewItem() method which can be accessible from View_A_book() method in ShowEachBook Controller.

Here is my Controller in BookApp module

var bookApp = angular.module('bookApp', []);

bookApp.controller('bookListCtr', function ($scope, $http) {

    $scope.ViewItems = function ($id) {
        $this->View_A_book($id);// This is example because I want to used View_A_book() method here
    };
 })

And here is the ShowEachBook Controller

bookApp.controller('ShowEachBook', function ($scope, $http) {

  $scope.View_A_book = function($id){
       /// get book from server.
  }
})

Create a factory. You only have to define it once, and it can be injected and called from any controller. See this article .

--

Make a factory ViewBook , and add your function to it: Your factory:

angular.module('bookApp')
    .factory('ViewBook', function () {
        return {
            view_a_book: function(id) {
                //do whatever you want to.
                return something 
            },
        };
    });

Your controller:

var bookApp = angular.module('bookApp', []);

bookApp.controller('bookListCtr', function ($scope, $http, ViewBook) {

    $scope.ViewItems = function ($id) {
        ViewBook.view_a_book($id);
    };
 })

You add a reference to the factory with $scope and $http , and use that to call it. This can be repeated for any controllers you have.

You can write all the methods or functions which is common to your project as a Service. In angular js we can create 2 types of Services

  1. Factory
  2. Service

In your problem you just write the function 'View_A_Book' as a service and just inject this service to the controller which you want to use the function.

Please refer the below link to get the idea about Service and Factory

http://blog.thoughtram.io/angular/2015/07/07/service-vs-factory-once-and-for-all.html

To share info betwen controllers use a Service. But for your use case I sugess use ui-router with two states: list and list.detail each of them with specific controller. On url of detail map the id of the single item list/book/[id] and resolve ittrought a API request or list array from parent state.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM