programing

Angular의 'scope'를 사용하여 다른 컨트롤러에서 컨트롤러의 메서드를 호출합니다.JS

kingscode 2023. 3. 12. 12:23
반응형

Angular의 'scope'를 사용하여 다른 컨트롤러에서 컨트롤러의 메서드를 호출합니다.JS

를 사용하여 첫 번째 컨트롤러의 두 번째 컨트롤러의 메서드를 호출하려고 합니다.scope변수.첫 번째 컨트롤러의 메서드는 다음과 같습니다.

$scope.initRestId = function(){
        var catapp = document.getElementById('SecondApp');
        var catscope = angular.element(catapp).scope();
        catscope.rest_id = $scope.user.username;
        catscope.getMainCategories();
    }; 

값을 설정할 수 있습니다.rest_id전화를 할 수 없습니다.getMainCategories웬일인지 그래.콘솔에 다음 오류가 표시됩니다.

TypeError: 개체 번호에 'getMainCategories' 메서드가 없습니다.

위의 방법을 호출할 수 있는 방법이 있습니까?

편집:

두 개의 앱을 동시에 로드하기 위해 다음과 같은 방법을 사용했습니다.

angular.bootstrap(document.getElementById('firstAppID'), ['firstApp']);
angular.bootstrap(document.getElementById('secondAppID'), ['secondApp']);

물론 여기서 서비스를 이용할 수 있지만, 같은 서비스를 이용할 수 있는 다른 방법이 있는지 알고 싶습니다!

2개의 컨트롤러 간에 통신하는 최선의 방법은 이벤트를 사용하는 것입니다.

범위 문서

이 체크아웃에서는$on,$broadcast그리고.$emit.

일반적인 사용 사례:angular.element(catapp).scope()는 jquery 이벤트 내에서와 같이 각도 컨트롤러 외부에서 사용하도록 설계되었습니다.

이상적인 사용법은 다음과 같이 컨트롤러 1에 이벤트를 쓰는 것입니다.

$scope.$on("myEvent", function (event, args) {
   $scope.rest_id = args.username;
   $scope.getMainCategories();
});

두 번째 컨트롤러에서는

$scope.initRestId = function(){
   $scope.$broadcast("myEvent", {username: $scope.user.username });
};

편집: 두 모듈 간의 통신임을 깨달았습니다.

이 부분을 포함시켜 주시겠어요?firstApp에 대한 의존관계로서secondApp당신이 선언하는 장소angular.module이렇게 하면 상대방 앱과 통신할 수 있습니다.

다음은 디렉티브 및 기타 컨트롤러에서 공유 서비스를 사용하는 방법에 대한 좋은 데모입니다.$scope.$on

HTML

<div ng-controller="ControllerZero">
    <input ng-model="message" >
    <button ng-click="handleClick(message);">BROADCAST</button>
</div>

<div ng-controller="ControllerOne">
    <input ng-model="message" >
</div>

<div ng-controller="ControllerTwo">
    <input ng-model="message" >
</div>

<my-component ng-model="message"></my-component>

JS

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

myModule.factory('mySharedService', function($rootScope) {
    var sharedService = {};

    sharedService.message = '';

    sharedService.prepForBroadcast = function(msg) {
        this.message = msg;
        this.broadcastItem();
    };

    sharedService.broadcastItem = function() {
        $rootScope.$broadcast('handleBroadcast');
    };

    return sharedService;
});

같은 방법으로 우리는 지시적으로 공유 서비스를 사용할 수 있습니다.컨트롤러 섹션을 디렉티브로 구현하여 사용할 수 있습니다.$scope.$on

myModule.directive('myComponent', function(mySharedService) {
    return {
        restrict: 'E',
        controller: function($scope, $attrs, mySharedService) {
            $scope.$on('handleBroadcast', function() {
                $scope.message = 'Directive: ' + mySharedService.message;
            });
        },
        replace: true,
        template: '<input>'
    };
});

여기 3개의 컨트롤러가 있습니다.ControllerZero호출하는 트리거로 사용되다prepForBroadcast

function ControllerZero($scope, sharedService) {
    $scope.handleClick = function(msg) {
        sharedService.prepForBroadcast(msg);
    };

    $scope.$on('handleBroadcast', function() {
        $scope.message = sharedService.message;
    });
}

function ControllerOne($scope, sharedService) {
    $scope.$on('handleBroadcast', function() {
        $scope.message = 'ONE: ' + sharedService.message;
    });
}

function ControllerTwo($scope, sharedService) {
    $scope.$on('handleBroadcast', function() {
        $scope.message = 'TWO: ' + sharedService.message;
    });
}

ControllerOne그리고.ControllerTwo들어봐message사용함으로써 변화하다$scope.$on핸들러

컨트롤러마다 범위가 다르기 때문에 문제가 발생합니다.

같은 데이터에 액세스필요가 있다2개의 컨트롤러를 가지는 은, 서비스를 필요로 하는 전형적인 신호입니다.각진 팀은 뷰와 서비스 사이의 접착제일 뿐인 씬 컨트롤러를 권장합니다.구체적으로는 "서비스는 컨트롤러 간에 공유 상태를 유지해야 합니다."

다행히 정확히 이 내용을 설명하는 15분짜리 비디오가 있습니다(컨트롤러와 서비스를 통한 통신).비디오

Angular의 원작자 중 한 명인 Misko Hebery는 Angular Best Practices라는 제목의 강연에서 (이 상황에서 서비스를 사용하는 것에 대한) 이 권장 사항에 대해 설명합니다(이 주제는 28:08로 건너뛰지만, 전체 토크를 볼 것을 강력히 권장합니다).

이벤트를 사용할 수 있지만 이벤트는 분리하려는 두 당사자 간의 통신만을 위해 설계되었습니다.위의 비디오에서 Misko는 앱을 더욱 취약하게 만드는 방법에 대해 설명합니다."대부분의 경우 서비스를 투입하고 직접 커뮤니케이션을 하는 것이 선호되고 더욱 견고합니다."(53:37부터 위의 링크를 체크하여 그가 말하는 것을 들어보십시오.)

언급URL : https://stackoverflow.com/questions/19468334/call-a-method-of-a-controller-from-another-controller-using-scope-in-angularjs

반응형