2015-01-27 4 views
2
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(); 
    }) 

나는 각도 JS에서 초보자이므로 코드 작성을 안내하겠습니다.AngularJS에서 Controller 2의 컨트롤러 1에 대한 액세스 방법

+3

아니요 두 번째 컨트롤러에서 액세스 할 수 없지만 기능을 공유하고 싶다면 b/w cont 롤러는 각도 서비스를 만듭니다. – squiroid

답변

2

AngularJS에서는 이러한 종류의 서비스에 대해 서비스를 사용합니다.

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

그리고 다른 컨트롤러에서 같은 : 그런 다음 종속성으로 본 서비스를 사용

.service('myService', function() { 
    return function() { 
     //your function1 
    }; 
}) 

:

그냥 여러 번 사용하고자하는 기능과 서비스를 만들

.controller('controller1', [ 
    '$scope', 
    'myService', 
    function($scope,myService) { 
     $scope.function1 = myService;//bind the service to the scope 
    } 
]) 
+0

또한 여러 함수가있는 서비스가 필요한 경우 함수 변수가있는 객체를 반환하고 어디서든 'myService.niceFunction()'과 같이 호출하면됩니다. – DonJuwe

+0

@DonJuwe 물론 다른 기능을 다른 곳에서도 사용하는 경우보다 똑똑합니다. – Nano

관련 문제