AngularJS Controllers

AngularJS Controllers

Controllers are where all your application logic and behavior live.

They control the data flow between the view and the background services.


What is a Controller?

A controller is simply a standard JavaScript object created by a constructor function.

You define a controller inside an AngularJS module using the .controller() method.

It uses the $scope object to expose variables and functions to the HTML view.


Using ng-controller

To attach a controller to an HTML element, you use the ng-controller directive.

Everything inside that specific HTML element will have access to the controller's data!

This enforces excellent separation of concerns.

Controller Example:

<div ng-app="myApp" ng-controller="myCtrl">
  <p>First Name: {{ firstName }}</p>
  <p>Last Name: {{ lastName }}</p>
</div>

<script> var app = angular.module('myApp', []); app.controller('myCtrl', function($scope) { $scope.firstName = "John"; $scope.lastName = "Doe"; }); </script>


SEO and Best Practices

Controllers help keep your JavaScript cleanly separated from your HTML markup.

Clean HTML is significantly easier for Google to crawl and index effectively.

Keep your controllers thin; move heavy data-fetching logic into Services!


Exercise 1 of 1

?

Which object is injected into a controller to share data with the HTML view?