Created
February 19, 2013 19:21
-
-
Save fdietz/4988964 to your computer and use it in GitHub Desktop.
Recipes with Angular.js: Controllers - Sharing Code Between Controllers using Services
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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