AngularJS - $timeout and resolve
promises, initial content then updated
by Krzysztof Safjanowski
HTML
<script src="https://code.angularjs.org/1.2.1/angular-route.js"></script>
<div ng-app='app'>
<div ng-controller='withoutRouting as ctrl'>
without routing: {{ ctrl.text.content }}
</div>
<div ng-view=""></div>
</div>
JavaScript
angular.module('app', ['ngRoute'])
.config(function($routeProvider, $locationProvider) {
$locationProvider.html5Mode(true);
$routeProvider.when('/content', {
template: ['<div>', '<p>content: {{ ctrl.text.content }}</p>', '</div>'].join(''),
controller: 'controller',
controllerAs: 'ctrl',
resolve: {
content: function(contentFactory) {
return contentFactory.getText()
}
}
}).otherwise({
redirectTo: '/content'
});
})
.service('contentFactory', function($timeout) {
this.text = {
content: 'first content'
}
this.getText = function() {
return $timeout(function() {
return this.text;
}.bind(this), 1000)
}
$timeout(function() {
this.text.content = 'second content'
}.bind(this), 2000);
})
.controller('controller', function(content) {
this.text = content;
})
.controller('withoutRouting', function(contentFactory) {
this.text = {
content: 'initial content'
}
contentFactory.getText().then(function(response) {
this.text = response
}.bind(this))
})