无法获取控制器之间共享的对象

时间:2014-08-27 15:46:50

标签: angularjs ionic-framework

我试图用工厂在两个控制器之间共享一个对象。我可以正确存储对象,但是当我尝试从主控制器获取它时,它表示对象是空的(未定义)。我希望得到一些反馈。

var app = angular.module('wgot', ['ionic'])

.config(function($stateProvider, $urlRouterProvider) {

  $stateProvider
    .state('splash', {
      url: "/",
      templateUrl: "templates/splashscreen.html"
    })

    .state('settings', {
      url: "/settings",
      templateUrl: "templates/settings.html"
    })

    .state('main', {
      url: '/main',
      templateUrl: 'templates/main.html'
    })

  $urlRouterProvider.otherwise('/');

})

.factory('TT', function(){
  var savedData = {}
  function set(data) {
    savedData = data;
  }
  function get() {
    return savedData;
  }
  return {
    set: set,
    get: get
  }
})

.controller('SettingsCtrl', function($scope, $http, TT){

  $scope.regions = [
    {name : 'United Arab Emirates', id : '23424738'}
    ];

  $scope.region = $scope.regions[0];

  $scope.requestTT = function() {
    $http.get(/* url */ + $scope.region.id).success(function (data){
      TT.set(data);
    })
  };
})
.controller('MainCtrl', function($scope, TT){
  //Here TT.get() doesn't return the value that I've stored previously
  $scope.words = TT.get();
  var words = [];
  var listLength = $scope.words.list[0]['trends'].length;
  for (var i = 0; i < listLength; i++) {
    words[i] = $scope.words.list[0]['trends'][i].name;
  };
  this.words = words;
});

这是观点:

<ion-view class= "splashscreen" ng-controller="SettingsCtrl">
<ion-content class = "content" scroll="false">
<div class="bar bar-header bar-light">
  <h1 class="title">Settings</h1>
</div>
<div class="list card list-card">
    <label class="item item-input item-select">
      <div class="input-label">
        Country
      </div>
      <select ng-model="region" ng-options="region.name for region in regions">
        <option value="">-- choose a region --</option>
      </select>
    </label>
    <a class="item item-icon-right assertive" ui-sref="main" ng-click="requestTT()">
      <i class="icon ion-radio-waves"></i>
      Start receiving
    </a>
</div>
</ion-content>
</ion-view>

第二个控制器是无法获取对象的控制器。

<ion-view class = "main">
  <ion-content>
    <div class="os-phrases" ng-controller="MainCtrl as main">
      <h2 ng-repeat="word in main.words" ng-bind-html='word | lettering'></h2>
    </div>
  </ion-content>
</ion-view>

1 个答案:

答案 0 :(得分:1)

我认为问题在于,当您从主控制器中的服务中读取数据时,尚未为其分配任何内容,解决此问题的一种方法是查看主服务器内的服务中的数据控制器:

$scope.$watch(TT.get,function(v){
   $scope.words = v;
})