[英]Using Values of an Angular Controller in Two Different Pages
我有两个不同的页面。 我们将其名称命名为product.php
和buy.php.
我有一个controllerProduct
为product.php
和controllerBuy
为buy.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 $的产品,最后单击了购买按钮, buy.php
将加载buy.php
页面。
在buy.php
我想向用户显示以下内容:
“嘿,用户,您将购买此产品!其价格为{{price}}$
”。
如何在controllerBuy中使用controllerProduct中的price变量?
每当您想在控制器之间共享逻辑时,这都是服务的理想选择。
一般的方法可能是这样
//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;
})
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.