【问题标题】:Using Values of an Angular Controller in Two Different Pages在两个不同页面中使用 Angular 控制器的值
【发布时间】:2017-10-11 08:15:14
【问题描述】:

我有两个不同的页面。让他们的名字是product.phpbuy.php. 我有一个controllerProduct 用于product.phpcontrollerBuy 用于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 我想向用户展示这样的内容:

“嘿用户,你要买这个产品!它的价格是{{price}}$”。

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

【问题讨论】:

  • 您只需将价格数据保存在浏览器存储中。因此,您可以在另一个页面上检索它。

标签: javascript php angularjs controller


【解决方案1】:

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

一般的方法可能是这样的

 //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;
  })
})

【讨论】:

  • 在 product.php 页面上加载具有 controllerProduct 的 product.js,在 buy.php 页面上加载具有 controllerBuy 的 buy.js。我应该把 shareService 放在哪里?
  • 你可以创建一个不同的文件
猜你喜欢
  • 2023-03-03
  • 2013-04-20
  • 1970-01-01
  • 2018-09-27
  • 2016-10-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多