Using services to create application data to be shared among different controllers or different scopes.
something like a global javascript variable in a single page app. not really session variable as the variable will reset after the page is refreshed.
HTML:
<html data-ng-app="demoApp" >
<head>
<title>Angular Demo</title>
</head>
<body data-ng-controller="MyController">
<h1>Hello Angular</h1>
<ul>
<li><a ng-click="myMethod('clicked')" href="#/SecondPage">second page</a></li>
<li><a href="#/ThirdPage">third page</a></li>
</ul>
<div ng-view></div>
<script src="angular.min.js"></script>
<script src="angular-route.min.js"></script>
<script src="test01.js"></script>
</body>
</html>
JS:
var demoApp = angular.module('demoApp', ['ngRoute']);
// add service as dependencies
demoApp.controller('MyController', ['$scope', 'myService', '$route',
// add service as parameter
function($scope, myService, $route){
console.log("MyController");
$scope.mydata = myService; // add service object to scope
$scope.myMethod = function(special){
console.log("myMethod called: " + special);
myService.age++;
myService.phone.price += 0.1;
myService.addFriend("Friend " + myService.age);
console.log(myService);
};
}]);
//Define Routing for app
demoApp.config(['$routeProvider',
function($routeProvider) {
$routeProvider.
when('/SecondPage', {
templateUrl: 'second.html',
controller: 'MyController' // can be different
}).
when('/ThirdPage', {
templateUrl: 'third.html',
controller: 'MyController' // can be different
}).
otherwise({
redirectTo: '/SecondPage'
});
}]);
// service
demoApp.factory('myService', function() {
console.log("service starting");
// object of this service
var mydata = {
// add properties
name: "My Data",
age: 30,
friends: ["Tarth Bader", "Koda", "Kan zolo"],
phone: {brand: "orange", model: "oPhone Plus", price:2000},
};
// add methods
mydata.addFriend = function(friend){
this.friends.push(friend);
};
// return service
return mydata;
});
second.html:
<div>{{ mydata.name }} is of {{mydata.age}}</div>
<ul>
<li ng-repeat="friend in mydata.friends">{{friend}}</li>
</ul>