在控制器中共享范围数据

时间:2017-01-30 10:56:37

标签: angularjs

我的spring mvc控制器返回一个对象。 我的情况是: 点击一个页面上的按钮,说sample1.html以表格的形式加载一个新页面说sample2.html。

在带有button1和controller1的sample1.html中 - >单击button1 - >后,我在controller1中获得了对象(假设我是从后端获得的)。 但是应该使用相同的对象来显示sample2.html中的表

我们如何使用sample2.html中controller1中的这个对象?

2 个答案:

答案 0 :(得分:1)

您可以使用服务存储数据,并将其注入控制器。然后,当值更新时,您可以使用support.office.com进行分享。

以下是一些例子:

HTML视图

<div ng-controller="ControllerOne">
  CtrlOne <input ng-model="message">
  <button ng-click="handleClick(message);">LOG</button>
</div>

<div ng-controller="ControllerTwo">
  CtrlTwo <input ng-model="message">
</div>

<强>控制器

function ControllerOne($scope, sharedService) {
  $scope.handleClick = function(msg) {
    sharedService.prepForBroadcast(msg);
  };
}

function ControllerTwo($scope, sharedService) {
  $scope.$on('handleBroadcast', function() {
    $scope.message = sharedService.message;
  });
}

<强>服务

myModule.factory('mySharedService', function($rootScope) {
  var sharedService = {};

  sharedService.message = '';

  sharedService.prepForBroadcast = function(msg) {
    this.message = msg;
    this.broadcastItem();
  };

  sharedService.broadcastItem = function() {
    $rootScope.$broadcast('handleBroadcast');
  };
  return sharedService;
});

broadcast event

答案 1 :(得分:-1)

您可以使用factory在控制器之间共享数据

    <div ng-controller="CtrlOne"> 

      <button ng-click="submit()">submit</button>
    </div>

    <div ng-controller="CtrlTwo">
       {{obj}}
    </div>

.controller('CtrlOne', function($scope, sampleFactory) {
      $scope.sampleObj = {
          'name': 'riz'
      }; //object u get from the backend
      $scope.submit = function() {
          sampleFactory.setObj($scope.sampleObj);
      }
  })
  .controller('CtrlTwo', function($scope, sampleFactory) {
      $scope.obj = sampleFactory.getObj();
  })
  .factory('sampleFactory', function() {
      var obj = {};
      return {
          setObj: function(_obj) {
              obj = _obj;
          },
          getObj: function() {
              return obj;
          }
      }
  })
相关问题