简体   繁体   English

如何在angularjs中从另一个控制器调用一个控制器的功能?

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

I want to call Listing function of testController from userController. 我想从userController调用testController的Listing函数。 I mark(//) the place from where i want to call function in following code. 我在以下代码中标记(//)我要从中调用函数的位置。 I am doing this in angularjs 我在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;
                    });
                }
    }

If you nest these two controllers in your markup, you can access the parent scope functions in the child controller. 如果将这两个控制器嵌套在标记中,则可以访问子控制器中的父作用域函数。 If not, this function might not belong into a controller, but a service, provider or factory. 如果不是,此功能可能不属于控制器,而是服务,提供者或工厂。

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

  </div>
</div>

You can also define services that you can then provide to your controllers. 您还可以定义服务 ,然后可以提供给您的控制器。 Here you could define a service userManagement: 在这里您可以定义服务userManagement:

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

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

This service will be accessible in your controller like this: 可以通过以下方式在您的控制器中访问此服务:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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