내용으로 건너뛰기
AngularJS에서 컨트롤러 간에 데이터를 공유하는 방법

AngularJS에서 컨트롤러 간에 데이터를 공유하는 방법

AngularJS 수업에서 종종 "AngularJS의 컨트롤러간에 데이터를 공유하려면 어떻게해야합니까?"라는 질문을받습니다. 인터넷에는 많은 솔루션이 제안되어 있습니다.

2min read

AngularJS 수업에서 종종 "AngularJS의 컨트롤러간에 데이터를 공유하려면 어떻게해야합니까?"라는 질문을받습니다. 인터넷에는 많은 솔루션이 제안되어 있습니다.

그러나 저는 Shared Data Service 방법을 사용하여 데이터를 공유하는 것을 선호하며 이것이 이 게시물에서 살펴볼 내용입니다.

먼저 컨트롤러 간에 Product 개체를 공유한다고 가정해 보겠습니다. 여기서 아래 스 니펫과 같이 SharedDataService 라는 AngularJS 서비스를 만들었습니다.

myApp.service('SharedDataService', function () {
     var Product = {
        name: '',
        price: ''
    };
    return Product;
});

다음으로 SharedDataService를 사용하여 두 개의 다른 컨트롤러를 만들어 보겠습니다. 컨트롤러에서는 이전 단계에서 만든 서비스를 사용하고 있습니다. 컨트롤러는 아래와 같이 생성할 수 있습니다.

var myApp = angular.module("myApp", ['CalService']);
 
myApp.controller("DataController1", ['$scope', 'SharedDataService',
    function ($scope, SharedDataService) {
       $scope.Product = SharedDataService;
    }]);
myApp.controller("DataController2", ['$scope', 'SharedDataService',
    function ($scope, SharedDataService) {
    $scope.Product = SharedDataService;
}]);

보기에서 아래 목록에 표시된 대로 컨트롤러를 간단히 사용할 수 있습니다.

<div ng-controller="DataController1">
            <h2>In Controller 1</h2>
            <input type="text" ng-model="Product.name" /> <br/>
            <input type="text" ng-model="Product.price" />
            <h3>Product {{Product.name}} costs {{Product.price}} </h3>
        </div>
        <hr/>
        <div ng-controller="DataController2">
            <h2>In Controller 2</h2>
            <h3>Product {{Product.name}} costs {{Product.price}} </h3>
        </div>

이제 컨트롤러 간에 데이터를 공유할 수 있습니다. 보시다시피 제품의 이름과 가격은 DataController1에서 설정되고 있으며 DataController2에서 데이터를 가져오고 있습니다.

데이터를 공유하는 데 사용하는 더 나은 옵션이 있습니까? 또는 위의 접근 방식으로 해결되지 않을 수 있는 복잡한 시나리오가 있을 수 있습니다. 그렇다면 알려주세요! 아래 의견에 대해 알려주십시오.

데모 요청