更新控制器之间的共享数据

时间:2017-01-06 05:09:28

标签: javascript angularjs angular-services angular-controller data-sharing

我试图在AngularJS控制器之间实现数据共享,我已经采用了在两个控制器之间共享服务实例的方法,并且它没有问题,来自变量的数据显示起来。但是,现在我需要从服务更新变量,以便各种控制器复制更改,因此注入相同服务的任何控制器都具有相同的数据。

这是我尝试实现这一目标......

HTML模板

<h1>Services data sharing</h1>
<div ng-controller="OrderListController as vm">
  <h3>Orders list</h3>
  <table>
    <tr>
      <th>Item name</th>
      <th>Total</th>
    </tr>
    <tr ng-repeat="order in vm.orders" ng-click="vm.selectOrder(order.id)">
      <td ng-bind="order.item"></td>
      <td ng-bind="order.total | currency"></td>
    </tr>
  </table>
  <p><i>Click an order to see it's details.</i></p>
</div>
<div ng-controller="OrderShowController as vm">
  <h3>Order detail</h3>
  <p>
    <b>ID: </b><span ng-bind="vm.order.id"></span>
  </p>
  <p>
    <b>Item name: </b><span ng-bind="vm.order.item"></span>
  </p>
  <p>
    <b>Total: </b><span ng-bind="vm.order.total | currency"></span>
  </p>
</div>

JavaScript文件

'use strict';

angular
    .module('orderCrud', [])
    .service('OrderService', function() {

        this.selected = {};

        var orders = [{
            id: 1,
            item: 'Hamburger',
            total: 5.15
        }, {
            id: 2,
            item: 'Nachos',
            total: 2.75
        }, {
            id: 3,
            item: 'Hot Dog',
            total: 3.50
        }];

        function getOrders() {

            return orders;
        }

        function setSelected(id) {

            for (var i = orders.length - 1; i >= 0; i--) {

                if (orders[i].id === id) {
                    this.selected = orders[i];
                    console.log(this.selected);
                    break;
                }
            }
        }

        return {
            get: getOrders,
            setSelected: setSelected
        };
    })
    .controller('OrderListController', function(OrderService) {

        var vm = this;

        vm.orders = OrderService.get();

        vm.selectOrder = function(id) {

            OrderService.setSelected(id);
        };

        vm.selectOrder(angular.copy(vm.orders).shift().id);
    })
    .controller('OrderShowController', function(OrderService) {

        var vm = this;

        vm.order = OrderService.selected;
    });

I've created a Plunker if you need it

目标是在模板的详细信息侧显示所选订单,如果在列表中的表中单击了其他订单,则应更改该订单。正如您可能注意到的那样,我不是控制器中$scope$rootScope的粉丝,如果没有注入这些示波器就没有任何方法可以实现这一点,请让我知道。

任何帮助都将受到高度赞赏,谢谢!

1 个答案:

答案 0 :(得分:0)

我做了一些代码更改:

  • for loop服务方法中使用了javaScript filter()方法而不是 setOrders
  • 使用$scope.$watch函数根据旧值和新值更改将服务数据反映到另一个控制器中。

工作演示:

&#13;
&#13;
angular
  .module('orderCrud', [])
  .service('OrderService', function() {
    
    this.selected = {};
    
    var orders = [{
      id: 1,
      item: 'Hamburger',
      total: 5.15
    }, {
      id: 2,
      item: 'Nachos',
      total: 2.75
    }, {
      id: 3,
      item: 'Hot Dog',
      total: 3.50
    }];
    
    var selectedOrder = [];
    
    this.getOrders = function() {
      
      return orders;
    }
    
    this.getSelectedOrder = function() {
      return selectedOrder;
    }
    
    this.setOrders = function(id) {
          this.order = orders.filter(function(item) {
            return item.id === id;
          });
          selectedOrder = this.order[0];
    }
    
  })
  .controller('OrderListController', function($scope, OrderService) {
    
    $scope.orderServ = OrderService;
    var vm = this;
    
    vm.orders = $scope.orderServ.getOrders();
    
    vm.selectOrder = function(id) {
      $scope.orderServ.setOrders(id);
    };
    
  }).controller('OrderShowController', function($scope, OrderService) {
    
    var vm = this;
    
    $scope.orderServ = OrderService;
    
    $scope.$watch(function () { return $scope.orderServ.getSelectedOrder(); }, function (newValue, oldValue) {
        if (newValue !== oldValue) vm.order = newValue;
    });
    
  });
&#13;
table {
    font-family: arial, sans-serif;
    border-collapse: collapse;
    width: 100%;
}

td, th {
    border: 1px solid #dddddd;
    text-align: left;
    padding: 8px;
}

tr:nth-child(even) {
    background-color: #dddddd;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body ng-app="orderCrud">
    <h1>Services data sharing</h1>
    <div ng-controller="OrderListController as vm">
      <h3>Orders list</h3>
      <table>
        <tr>
          <th>Item name</th>
          <th>Total</th>
        </tr>
        <tr ng-repeat="order in vm.orders" ng-click="vm.selectOrder(order.id)">
          <td ng-bind="order.item"></td>
          <td ng-bind="order.total | currency"></td>
        </tr>
      </table>
      <p><i>Click an order to select it.</i></p>
      </div>
<div ng-controller="OrderShowController as vm">
      <h3>Order detail</h3>
      <p>
        <b>ID: </b><span ng-bind="vm.order.id"></span>
      </p>
      <p>
        <b>Item name: </b><span ng-bind="vm.order.item"></span>
      </p>
      <p>
        <b>Total: </b><span ng-bind="vm.order.total | currency"></span>
      </p>
          </div>
  </body>
&#13;
&#13;
&#13;