簡體   English   中英

如何在angularjs中從另一個控制器調用一個控制器的功能?

[英]How to call function of one controller from other controller in angularjs?

我想從userController調用testController的Listing函數。 我在以下代碼中標記(//)我要從中調用函數的位置。 我在angularjs中這樣做

function userController($scope, $http) {

                $scope.SignUp = function() {

                    $http.post('<?php echo site_url('angularjs/addToTable'); ?>', {'uname': $scope.username, 'pswd': $scope.userpassword, 'email': $scope.useremail}
                    ).success(function(data, status, headers, config) {

                        // Here i want to call Listing function of testController ...
                    });
                }
    }
    function testController($scope, $http) {
        $scope.Listing = function() {
                    $scope.users = [];
                    $http.get('<?php echo site_url('angularjs/get_list'); ?>').success(function($data) {

                        $scope.users = $data;
                    });
                }
    }

如果將這兩個控制器嵌套在標記中,則可以訪問子控制器中的父作用域函數。 如果不是,此功能可能不屬於控制器,而是服務,提供者或工廠。

<div ng-controller="testController">
  <div ng-controller="userController">

  </div>
</div>

您還可以定義服務 ,然后可以提供給您的控制器。 在這里您可以定義服務userManagement:

myModule.service('UserManagement', function() {
    this.list = function() {
        //..
    }

    this.signUp = function() {
        //..
    }
  });

可以通過以下方式在您的控制器中訪問此服務:

testController($scope, $http, UserManagement){
 // insert code here
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM