AngularJS Controllers: The Brains Behind the App - FadiZahhar/AngularJs GitHub Wiki

The StartApp Team Gets Organized


Scene: The Code Review

The StartApp team’s Task Manager app is working great—inputs update instantly, lists grow, and calculations update live. But their HTML is getting cluttered with variables, ng-init, and repeated logic.

Mike (Team Lead): “I love how fast we can prototype, but our HTML is getting messy. There’s got to be a way to separate logic from the markup.”

Sara (Junior Dev, reading docs): “AngularJS uses controllers to hold the app’s logic and data. Controllers keep everything organized and reusable!”


What is an AngularJS Controller?

  • A controller is a JavaScript function that manages the data and logic for part of an AngularJS app.
  • You define controllers in your JS, and connect them to your HTML with ng-controller.

1. Creating a Controller: Step by Step

Step 1: Define a Module

var app = angular.module('taskApp', []);

Step 2: Add a Controller to the Module

app.controller('taskCtrl', function($scope) {
  $scope.greeting = "Welcome to the Task Manager!";
});

Step 3: Connect the Controller to the HTML

<div ng-app="taskApp" ng-controller="taskCtrl">
  <h2>{{ greeting }}</h2>
</div>

Result: The view displays “Welcome to the Task Manager!” You can change $scope.greeting in your controller, and the view updates.


2. Why Use Controllers? (Team Discussion)

  • Sara: “All the data and logic is in the controller, so our HTML just displays stuff.”
  • Lina (Designer): “Easier for me to update the layout without breaking the app logic.”
  • Mike: “We can reuse controllers on different parts of the page, or even in other projects.”

3. Working with Data: Lists, Methods, and More

a. Managing a Task List

app.controller('taskCtrl', function($scope) {
  $scope.tasks = ["Design logo", "Setup database", "Write docs"];
});
<ul>
  <li ng-repeat="t in tasks">{{ t }}</li>
</ul>

b. Adding Methods to the Controller

app.controller('taskCtrl', function($scope) {
  $scope.tasks = [];
  $scope.addTask = function() {
    if ($scope.newTask) {
      $scope.tasks.push($scope.newTask);
      $scope.newTask = "";
    }
  };
});
<input ng-model="newTask" placeholder="New Task">
<button ng-click="addTask()">Add Task</button>
<ul>
  <li ng-repeat="t in tasks">{{ t }}</li>
</ul>

Result: The list updates as tasks are added—no cluttered HTML or JS outside the controller!


4. Multiple Controllers on One Page

Mike: “We can have more than one controller if needed. For example, a separate controller for user profile data:”

app.controller('userCtrl', function($scope) {
  $scope.name = "Lina";
  $scope.email = "[email protected]";
});
<div ng-controller="userCtrl">
  <p>User: {{ name }}</p>
  <p>Email: {{ email }}</p>
</div>

5. Team Challenge: Refactor with Controllers

Take a messy page full of ng-init and variables, and move all the data and logic into a controller.

Before (Messy):

<div ng-app ng-init="title='Demo'; desc='Try me!'">
  <h2>{{ title }}</h2>
  <p>{{ desc }}</p>
</div>

After (With Controller):

<div ng-app="demoApp" ng-controller="demoCtrl">
  <h2>{{ title }}</h2>
  <p>{{ desc }}</p>
</div>
<script>
  var app = angular.module('demoApp', []);
  app.controller('demoCtrl', function($scope) {
    $scope.title = "Demo";
    $scope.desc = "Try me!";
  });
</script>

6. Key Takeaways

  • Controllers help separate concerns: logic and data in JS, layout in HTML.
  • $scope is the glue that connects data from the controller to the view.
  • Using controllers makes your app more scalable, reusable, and maintainable.

Full Example: Task Manager with Controller

<!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">
  <h2>{{ greeting }}</h2>
  <input ng-model="newTask" placeholder="New Task">
  <button ng-click="addTask()">Add Task</button>
  <ul>
    <li ng-repeat="t in tasks">{{ t }}</li>
  </ul>
</div>
<script>
  var app = angular.module('taskApp', []);
  app.controller('taskCtrl', function($scope) {
    $scope.greeting = "Welcome to the Task Manager!";
    $scope.tasks = ["Design logo", "Setup database", "Write docs"];
    $scope.addTask = function() {
      if ($scope.newTask) {
        $scope.tasks.push($scope.newTask);
        $scope.newTask = "";
      }
    };
  });
</script>
</body>
</html>

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


Looking Ahead

Mike: “Now our app logic is clean and ready for more advanced features—like services and REST APIs!”

Sara: “Let’s explore services and see how to organize even more code outside of controllers.”

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