I'm trying to share an object between two controllers with a factory. I can store the object correctly but when I try to get it from the main controller it says the object it's empty(undefined). I would appreciate some feedback.
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;
});
This are the views:
<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>
This second controller is the one that can't get the object.
<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>
I think the problem is that by the time you read the data from the service in the Main controller, nothing has been assigned to it yet, one way to work around this would be to watch the data in the service inside your Main controller:
$scope.$watch(TT.get,function(v){
$scope.words = v;
})