$timeout example
HTML
<script src="http://code.angularjs.org/1.0.0rc10/angular-1.0.0rc10.js"></script>
<div ng-controller="PrefsCtrl">
<p>Preferences:</p>
<input type='text' ng-change='changeFaveColor()' ng-model='prefs.faveColor'>
<button ng-click="checkService ()">Check Service faveColor</button>
<br>
<p>{{prefs.history.length}} items in history:</p>
<span ng-repeat="item in prefs.history">
{{$index + 1}}. {{item}} <span ng-hide="$last">|</span>
</span><br>
<input type='text' ng-model='newHistoryItem'>
<button ng-click="addToHistory()">Add to history</button>
</div>
CSS
.big{
font-size: 2em;;
}
.normal{
font-size: 1em;
}
.small{
font-size: .5em;
}
JavaScript
var app = angular.module('myApp', []);
app.run(function($rootScope, $timeout, otherService) {
console.log('starting run');
$timeout(function() {
otherService.updateTestService('Mellow Yellow')
console.log('update with timeout fired')
}, 3000);
alert("run");
});
app.service('otherService', function(testService, $timeout) {
this.updateTestService = function(color) {
testService.prefs.faveColor = color;
console.log('color changed to ' + color);
};
alert("otherService");
});
app.service('testService', function($rootScope) {
//object example
this.prefs = {
faveColor: "Green",
rememberMe: true,
history: ['history one', 'history two', 'history three'],
popIt: function() {
alert('fave color: ' + this.faveColor);
}
};
alert("testService");
});
function PrefsCtrl($scope, testService) {
//testService.prefs.popIt();
//object from service
$scope.prefs = testService.prefs;
$scope.checkService = function() {
testService.prefs.popIt();
};
$scope.newHistoryItem = '';
$scope.addToHistory = function() {
$scope.prefs.history.push($scope.newHistoryItem);
$scope.newHistoryItem = '';
};
alert("PrefsCtrl");
}