Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/472.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/blackberry/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript AngularJS中控制器2中控制器1的访问方法_Javascript_Angularjs - Fatal编程技术网

Javascript AngularJS中控制器2中控制器1的访问方法

Javascript AngularJS中控制器2中控制器1的访问方法,javascript,angularjs,Javascript,Angularjs,我是AngularJS的初学者,请指导我完成我的代码。在AngularJS中,您使用服务来完成这类工作 只需使用您想要多次使用的功能创建一个服务: angular.module('starter.controllers', []) .controller('controller1',function($scope) { $scope.function1= function () { --------------- }) .controller('c

我是AngularJS的初学者,请指导我完成我的代码。

在AngularJS中,您使用服务来完成这类工作

只需使用您想要多次使用的功能创建一个服务:

    angular.module('starter.controllers', [])
    .controller('controller1',function($scope) {
    $scope.function1= function () {
    ---------------
    })
    .controller('controller2',function($scope) {
    $scope.function1= function () {
    //is it possible to access method form controller1 in controller2 like this
controller1.function();
    })
然后将此服务用作依赖项:

.service('myService', function() {
    return function() {
        //your function1
    };
})
在另一个控制器中也是如此:

.controller('controller2', [
    '$scope',
    'myService',//say you want the service as second param
    function($scope, myService) {
        $scope.function1 = function() {
            myService();//your function is here
        };
    }
])

不,您不能在第二个控制器中访问它,但如果您希望这样的东西共享函数,b/w控制器会创建一个角度服务。此外,如果您需要一个具有多个函数的服务,只需返回一个带有函数变量的对象,并从任何地方调用它们,如
myService.niceFunction()
。@DonJuwe当然,如果他在其他地方也使用了其他功能,那么它就更聪明了
.controller('controller1', [
    '$scope',
    'myService',
    function($scope,myService) {
        $scope.function1 = myService;//bind the service to the scope
    }
])