Sharing Code Between Controllers using Services

by Akram kamal

HTML

<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
<link rel="stylesheet" href="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.min.css">
<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>

CSS

.nested {
  border: 1px solid red;
  margin-left: 2em;
  padding: 1em;
}

JavaScript

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();
});