AngularJS Services: Sharing Power Across the App - FadiZahhar/AngularJs GitHub Wiki

The StartApp Team Levels Up With Services


Scene: The Code Gets Messy

With the Task Manager app growing, Mike notices that both the Task and User controllers are copying the same logic for working with dates, formatting, and maybe even fetching task data.

Mike (Team Lead): “We’re repeating ourselves. Our controllers all need the same date formatter and maybe a way to save or load tasks in the future. AngularJS has ‘services’—let’s use them to keep code DRY and organized.”

Sara (Junior Dev): “So, a service is like a toolbox or helper we can use anywhere in our app?”


What is an AngularJS Service?

  • A service is a reusable object or function for sharing logic, data, or utilities across controllers and other parts of your app.
  • Built-in services include $http (for AJAX), $timeout, $interval, and more.
  • You can also create your own custom services!

1. Built-in Services Example: $http

Suppose the team wants to load tasks from a server.

Controller:

app.controller('taskCtrl', function($scope, $http) {
  $http.get("tasks.json").then(function(response) {
    $scope.tasks = response.data;
  });
});
  • $http is injected into the controller.
  • It fetches data and puts it on $scope for the UI.

2. Creating a Custom Service

The team wants a reusable tool for formatting task names.

Step 1: Define the Service

app.service('nameFormatter', function() {
  this.capitalize = function(str) {
    if (!str) return '';
    return str.charAt(0).toUpperCase() + str.slice(1);
  }
});

Step 2: Use the Service in a Controller

app.controller('taskCtrl', function($scope, nameFormatter) {
  $scope.taskName = "";
  $scope.formatName = function() {
    $scope.taskName = nameFormatter.capitalize($scope.taskName);
  };
});

HTML:

<input ng-model="taskName">
<button ng-click="formatName()">Capitalize</button>
<p>Formatted: {{ taskName }}</p>

3. Sharing Data with a Service

Sara: “If we put a shared task list in a service, all controllers can access and update it.”

Service:

app.factory('taskStore', function() {
  var store = {};
  store.tasks = [];
  store.addTask = function(task) {
    store.tasks.push(task);
  };
  return store;
});

Controller 1:

app.controller('addTaskCtrl', function($scope, taskStore) {
  $scope.newTask = "";
  $scope.addTask = function() {
    if ($scope.newTask) {
      taskStore.addTask($scope.newTask);
      $scope.newTask = "";
    }
  };
});

Controller 2:

app.controller('listTaskCtrl', function($scope, taskStore) {
  $scope.tasks = taskStore.tasks;
});

Now, adding a task in one controller updates the list in another!


4. Why Use Services? (Team Discussion)

  • Sara: “We don’t have to rewrite the same code everywhere.”
  • Lina (Designer): “If we want to change how we format names or dates, we do it in one place.”
  • Mike: “Services make our app scalable and easier to maintain.”

5. Key Takeaways

  • Services share logic and data across your app.
  • Built-in services like $http simplify AJAX calls.
  • Custom services let you create helpers, APIs, and shared state.

Full Example: Name Formatter Service

<!DOCTYPE html>
<html>
<head>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
</head>
<body>
<div ng-app="taskApp" ng-controller="taskCtrl">
  <input ng-model="taskName" placeholder="Type task">
  <button ng-click="formatName()">Capitalize</button>
  <p>Formatted: {{ taskName }}</p>
</div>
<script>
  var app = angular.module('taskApp', []);
  app.service('nameFormatter', function() {
    this.capitalize = function(str) {
      if (!str) return '';
      return str.charAt(0).toUpperCase() + str.slice(1);
    }
  });
  app.controller('taskCtrl', function($scope, nameFormatter) {
    $scope.taskName = "";
    $scope.formatName = function() {
      $scope.taskName = nameFormatter.capitalize($scope.taskName);
    };
  });
</script>
</body>
</html>

Try it live in the [W3Schools AngularJS TryIt Editor](https://www.w3schools.com/angular/angular_tryit.asp?filename=tryangular_services).


Team Conclusion

Mike: “Our code is cleaner and easier to reuse now. Next, let’s look at how AngularJS filters, sorts, and formats data in real time!”

⚠️ **GitHub.com Fallback** ⚠️