2015-01-25 4 views
1

Angular 애플리케이션에서 다음 상황에 직면하고 있습니다. 여기에 몇 가지 조언이 있습니다.컨트롤러 간 데이터 공유, AngularJS

일부 제품을 보여주는 페이지가 있는데이 페이지는 'ProductsController'라는 컨트롤러에서 관리합니다. 이 컨트롤러에는 'showProductDetails'라는 메서드가 있습니다.이 메서드는 사용자가 특정 제품을 클릭하면 호출되며이 메서드의 목표는 제품의 세부 정보를 검색하고 모달 패널에 이러한 세부 정보를 표시하는 것입니다. 여기까지는 특별한 것이 없습니다. 문제는 모듈성 때문에 다른 컨트롤러를 모달 패널에 부착하고 새 컨트롤러에서이 모달 패널의 모든 로직 (이 경우 'ProductDetailController')을 관리하고 싶습니다. 문제는 모달 패널을 열기 전에 제품의 데이터를 검색하는 것이지만 두 번째 컨트롤러에서 첫 번째 컨트롤러의 범위에서이 데이터를 검색 할 때 이전에 검색 한 제품에 액세스 할 수 없습니다. angularJs의 컨트롤러간에 데이터를 공유하는 것은 서비스를 통해 이루어 지지만 상태없는 서비스가 어떻게 도움이되는지는 알지 못합니다.

첫 번째 컨트롤러 :

app.controller('ProductsController', ['$scope','productsFactory','commonFactory','productsFactoryHelper','$filter','$modal',function ($scope,productsFactory,commonFactory,productsFactoryHelper,$filter,$modal) 
           { 




$scope.showProductDetails = function (size,product) { 

$scope.showLoader('Loading the details of the product. Please wait...'); 

productsFactoryHelper.Product.query({id:product.id},function(response) 
    { 
    $scope.selectedProduct=response; 
    $scope.hideLoader(); 
    var modalInstance = $modal.open({ 
      templateUrl: 'productDetail.html', 
      controller: 'ProductDetailController', 
      size: size 

     }); 
    },function(error) 
    { 
    commonFactory.Pop('error','This product is not available at this moment. Please try again later. If the problem persists contact a system administrator'); 
        $scope.hideLoader(); 
    }); 


}; 

_init();  
           }]); 

그리고 두 번째 컨트롤러 :

app.controller('ProductDetailController',['$scope','$modalInstance', function ($scope, $modalInstance) { 

           $scope.ok = function() { 
            $modalInstance.close(); 
           }; 

           $scope.cancel = function() { 
            $modalInstance.dismiss('cancel'); 
           }; 
           }]); 

그래서 기본적으로 질문에서 어떻게 접근 할 수있다 여기에

내 코드가 더 나은 상황을 이해하는 것입니다 'ProductDetailController'를 'ProductsController'의 범위에있는 'selectedProduct'객체로 가져옵니다.

도움 주셔서 감사합니다.

+0

chooseProduct로 컨트롤러를 만들고 변수에 $ watch를 첨부 할 수 있습니까? 그리고 두 개의 컨트롤러에 서비스를 삽입 하시겠습니까? – cyan

+1

[Angular : 컨트롤러간에 데이터 공유] 가능한 중복 (http://stackoverflow.com/questions/21919962/angular-share-data-between-controllers) –

답변

2

$ modal을 사용하여 데이터를 아래의 새 컨트롤러로 보내십시오. 나는 producfactory 도우미 제품 쿼리에 대해 잘 모릅니다

app.controller('ProductsController', ['$scope','productsFactory','commonFactory','productsFactoryHelper','$filter','$modal',function ($scope,productsFactory,commonFactory,productsFactoryHelper,$filter,$modal) 
             { 




    $scope.showProductDetails = function (size,product) { 

     $scope.showLoader('Loading the details of the product. Please wait...'); 

     productsFactoryHelper.Product.query({id:product.id},function(response) 
       { 
      $scope.selectedProduct=response; 
      $scope.hideLoader(); 
      var modalInstance = $modal.open({ 
       templateUrl: 'productDetail.html', 
       controller: 'ProductDetailController', 
       size: size, 
       resolve:{ 
        "selectedProduct":response 
       } 

      }); 
       },function(error) 
       { 
        commonFactory.Pop('error','This product is not available at this moment. Please try again later. If the problem persists contact a system administrator'); 
        $scope.hideLoader(); 
       }); 


    }; 

    _init();  
             }]); 

는 ..

$scope.showProductDetails = function (size,product) { 

    $scope.showLoader('Loading the details of the product. Please wait...'); 

    var modalInstance = $modal.open({ 
     templateUrl: 'productDetail.html', 
     controller: 'ProductDetailController', 
     size: size, 
     resolve:{ 
      "selectedProduct":productsFactoryHelper.Product.query({id:product.id}) 
     } 
    }); 
}; 

을 당신이 다음과 같이 사용할 수있는 약속이있는 경우 약속을 가지고 있으며 ProductDetailController에 당신은

다음과 같은이 selectedProduct를 삽입 할 수
app.controller('ProductDetailController',['$scope','$modalInstance','selectedProduct ' function ($scope, $modalInstance,selectedProduct) { 

    $scope.ok = function() { 
     $modalInstance.close(); 
    }; 

    $scope.cancel = function() { 
     $modalInstance.dismiss('cancel'); 
    }; 
}]); 
0

이것은 실제로는 서비스를 통해 수행 할 수 있습니다. 서비스를 통해 상태를 유지하고 데이터를 한 번 인스턴스화하기 때문입니다.

function productService($http) { 

    this.products = []; 

    this.loadProducts() { 
     $http.get('/url/to/your/product/api').then(function(err, data) {  
      this.products = data.products; 
     }); 
    }; 

    this.getProducts = function() { 
     return this.products; 
    } 
} 

angular 
    .module('yourModule') 
    .service('productService', productService); 

그러면 그냥 두 컨트롤러에서 productService를 주입 productService.loadProducts()를 사용하여 제품을로드하고 productService.getProducts()을 사용하여 얻을 수 있습니다.

이것은 단지 예입니다. 서비스를 사용하여 모든 종류의 데이터를 공유 할 수 있습니다.

0

실제로 서비스가 사용자에게 도움이되며, 데이터를 한 번 이상 액세스하지 않아도되는 경우 순수한 이벤트를 사용할 수 있습니다.

서비스를 사용하여 순수 종합 마술

app.controller('parentCtrl', function($scope) { 
    // Do something 

    // Action completed 
    @scope.$emit('someactionComplete', data); 
}); 

app.controller('childCtrl', function($scope) { 
    $scope.$on('someactionComplete', function(data) { 
     // Process data 
    }); 
}); 

. 서비스를 사용하면 데이터가 지속된다는 장점이 있습니다.

app.controller('parentCtrl', function($scope, MyService) { 
    // Do something 

    // Action completed 
    MyService.setData(data); 
    @scope.$emit('someactionComplete'); 
}); 

app.controller('childCtrl', function($scope) { 
    $scope.$on('someactionComplete', function() { 
     MyService.getData(data); 
    }); 
}); 

서비스가 데이터를로드하고 게터에서 약속을 반환하면이 기능을 향상시킬 수 있습니다.