Skip to content

Instantly share code, notes, and snippets.

@fdietz
Created February 19, 2013 19:21
Show Gist options
  • Save fdietz/4988964 to your computer and use it in GitHub Desktop.
Save fdietz/4988964 to your computer and use it in GitHub Desktop.
Recipes with Angular.js: Controllers - Sharing Code Between Controllers using Services
var app = angular.module("MyApp", []);
app.factory("UserService", function() {
var users = ["Peter", "Daniel", "Nina"];
return {
all: function() {
return users;
},
first: function() {
return users[0];
}
};
});
app.controller("MyCtrl", function($scope, UserService) {
$scope.users = UserService.all();
});
app.controller("AnotherCtrl", function($scope, UserService) {
$scope.firstUser = UserService.first();
});
<html>
<head>
<script src="js/angular.js"></script>
<script src="js/app.js"></script>
<link rel="stylesheet" href="css/bootstrap.css">
<style>
.nested {
border: 1px solid red;
margin-left: 2em;
padding: 1em;
}
</style>
</head>
<body ng-app="MyApp">
<div ng-controller="MyCtrl">
<ul ng-repeat="user in users">
<li>{{user}}</li>
</ul>
<div class="nested" ng-controller="AnotherCtrl">
First user: {{firstUser}}
</div>
</div>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment