Share Code Between Controllers using Services

Description

The following code shows how to share Code Between Controllers using Services.

Example


<!--from w w  w.j  av  a  2  s.  c  o  m-->
To share business logic between controllers,
use a Service to implement your business logic and use dependency injection to use this service in your controllers.

<!doctype html>
<html ng-app="MyApp">
<head>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.2/angular.js"></script>
    <script>
var app = angular.module("MyApp", []);

app.factory("UserService", function() {
  var users = ["A", "B", "C"];

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

Click to view the demo





















Home »
  AngularJS »
    AngularJS Example »




Controller
Directives
Expression
Filter
Form
Inject
Scope
Server
Style
Template
Utilities