Angular: Empty Fiddle
http://angularjs.org/
by techno2mahi
HTML
<script src="http://code.angularjs.org/angular-1.0.0.js"></script>
<div ng-controller="MyCtrl">
<input type="button" value="Add" ng-click="addValue(12)">
MyCtrl
{{hellos}}
VALUEctrl1 {{myValue}}
</div>
<div ng-controller="MyCtrl1">
<input type="button" value="Refresh" ng-click="refreshValue()">
MyCtrl1
{{hellos}}
VALUEctrl2 {{myValue}}
</div>
JavaScript
var myApp = angular.module('myApp', []);
//service style, probably the simplest one
myApp.factory('helloWorldFromService', function() {
var serviceValue = 100;
return {
sayHello = function() {
return "Hello, World!";
},
getValue = function(){
return serviceValue;
},
addValue = function(val){
serviceValue = serviceValue + val;
}
}
});
//factory style, more involved but more sophisticated
myApp.factory('helloWorldFromFactory', function() {
return {
sayHello: function() {
return "Hello, World!"
}
};
});
//provider style, full blown, configurable version
myApp.provider('helloWorld', function() {
this.name = 'Default';
this.$get = function() {
var name = this.name;
return {
sayHello: function() {
return "Hello, " + name + "!"
}
}
};
this.setName = function(name) {
this.name = name;
};
});
//hey, we can configure a provider!
myApp.config(function(helloWorldProvider){
helloWorldProvider.setName('World');
});
function MyCtrl($scope, helloWorld, helloWorldFromFactory, helloWorldFromService) {
$scope.myValue = helloWorldFromService.getValue();
$scope.addValue = function(val){
//alert(val);
helloWorldFromService.addValue(val);
}
helloWorldFromService.addValue(1);
$scope.hellos = [
helloWorld.sayHello(),
helloWorldFromFactory.sayHello(),
helloWorldFromService.sayHello()];
}
function MyCtrl1($scope, helloWorld, helloWorldFromService) {
$scope.myValue = helloWorldFromService.getValue();
$scope.refreshValue = function(){
//alert(val);
$scope.myValue = helloWorldFromService.getValue();
}
$scope.hellos = [
helloWorld.sayHello(),
helloWorldFromService.sayHello(),
helloWorldFromService.getValue()];
}