在两个不同页面中使用角度控制器的值

问题描述:

我有两个不同的页面。让我们的名字是product.phpbuy.php. 我有controllerProductproduct.phpcontrollerBuybuy.php在两个不同页面中使用角度控制器的值

用户加载product.php并选择要购买的产品,其价格为59美元。当他或她选择产品时,$scope.setPrice();功能在controllerProduct中运行。该setPrice功能如:

window.ngApp = angular.module('myApp', []); 
window.ngApp.controller('controllerProduct', ['$scope', 
    function ($scope) { 
      $scope.price = null //default 
      $scope.setPrice = function(){ 
       $scope.price = 59; 
      }; 
}]); 

现在,他或她所选择的产品,它的价格是$ 59和finaly点击购买按钮和buy.php页面将被加载。

buy.php我想告诉用户是这样的:“嘿用户,你要购买此产品,其价格是{{price}}$

如何在controllerBuy中使用controllerProduct中的price变量?

+0

你只是只需要节省浏览器存储价格的数据。所以,你可以在另一个页面上检索它。 – Rido

每次你想在控制器之间共享逻辑时,这是一个服务的完美场景。

的一般方法可能是这

//singleton to share logic between controllers 
.service('ShareService', function(){ 
var _price = null; 
this.setPrice = function(price){ 
    _price = price; 
} 
this.getPrice = function(){ 
    return _price; 
} 
}) 

//first controller 
.controller('controllerProduct', function($scope, ShareService){ 
    $scope.setPrice = function(price){ 
    $scope.price = price; 
    ShareService.setPrice(price); 
    }; 
}) 

//second controller 
.controller('controllerBuy', function($scope, ShareService){ 
    //watch changes of the price 
    $scope.$watch(function(){ 
    return ShareService.getPrice() 
    }, function(newVal){ 
    $scope.selectedPrice = newVal; 
    }) 
}) 
+0

在product.php页面上,product.js加载了一个controller.Product,在buy.php页面上,buy.js加载了一个controller.Build。我在哪里放shareService? – furkan7481

+0

你可以创建一个不同的文件 – Karim