Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Service example with AngularJS for sharing scope data between controllers
<!doctype html>
<html ng-app="project">
<title>Angular: Service example</title>
<script src=""></script>
var projectModule = angular.module('project',[]);
projectModule.factory('theService', function() {
return {
thing : {
x : 100
function FirstCtrl($scope, theService) {
$scope.thing = theService.thing;
$ = "First Controller";
function SecondCtrl($scope, theService) {
$scope.someThing = theService.thing;
$ = "Second Controller!";
<div ng-controller="FirstCtrl">
<input ng-model="thing.x"/>
<div ng-controller="SecondCtrl">
<input ng-model="someThing.x"/>
Copy link

nguyennm commented May 10, 2014


Copy link

pmanijak commented May 10, 2014

one test passed.

Copy link

slopjong commented Jun 22, 2014

second test passed.

Copy link

jurepolutnik commented Aug 28, 2014

segmentation fault

Copy link

igordelorenzi commented Sep 1, 2014

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

Copy link

pmanijak 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: It is neat.

Copy link

bennypowers commented Apr 4, 2016

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