Skip to content
Create a gist now

Instantly share code, notes, and snippets.

Service example with AngularJS for sharing scope data between controllers
<!doctype html>
<html ng-app="project">
<head>
<title>Angular: Service example</title>
<script src="http://code.angularjs.org/angular-1.0.1.js"></script>
<script>
var projectModule = angular.module('project',[]);
projectModule.factory('theService', function() {
return {
thing : {
x : 100
}
};
});
function FirstCtrl($scope, theService) {
$scope.thing = theService.thing;
$scope.name = "First Controller";
}
function SecondCtrl($scope, theService) {
$scope.someThing = theService.thing;
$scope.name = "Second Controller!";
}
</script>
</head>
<body>
<div ng-controller="FirstCtrl">
<h2>{{name}}</h2>
<input ng-model="thing.x"/>
</div>
<div ng-controller="SecondCtrl">
<h2>{{name}}</h2>
<input ng-model="someThing.x"/>
</div>
</body>
</html>
@nguyennm

test

@exclsr
Owner
exclsr commented May 10, 2014

one test passed.

@slopjong

second test passed.

@jurepolutnik

segmentation fault

@igordelorenzi

does it really work? how do you deal with concurrent access?

@exclsr
Owner
exclsr commented Sep 1, 2014

@0r1g Yeah, it works. In short, Angular "compiles" the JavaScript and HTML into its own "runtime-thing", where all services are singletons (i.e. one object for each service), and there's a model-view-update loop that fires events as things happen: https://docs.angularjs.org/guide/databinding. It is neat.

@bennyp123

Would this work when you have controllerAs syntax and don't have implicit inheritance?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.