Angular: Empty Fiddle
http://angularjs.org/
by Khalil Zhang
HTML
<script src="http://code.angularjs.org/angular-1.0.0.js"></script>
<div ng-controller="MyCtrl">{{name}}</div>
<div ng-controller="OtherCtrl">{{name}}</div>
JavaScript
var myApp = angular.module('myApp', []);
//service style, probably the simplest one
myApp.service('helloWorldFromService', function () {
debugger
this.name = "default";
this.setName = function (name) {
this.name = name;
};
this.sayHello = function () {
return "Hello, World!"
};
});
//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, helloWorldFromService) {helloWorldFromService.setName("xxxx");
$scope.name = helloWorldFromService.name;
}
function OtherCtrl($scope, helloWorldFromService) { $scope.name = helloWorldFromService.name;
}