</>
Skip to content
AngularJS lessons (6/28)

AngularJS — Controllers

Basic Controller

app.controller('MyController', function($scope) {
  $scope.name = 'John';
  $scope.greet = function() {
    return 'Hello, ' + $scope.name;
  };
});

Controller in HTML

<div ng-controller="MyController">
  <h1>{{name}}</h1>
  <p>{{greet()}}</p>
</div>

Controller Methods

app.controller('TodoController', function($scope) {
  $scope.todos = [];
  $scope.newTodo = '';
  
  $scope.addTodo = function() {
    if ($scope.newTodo) {
      $scope.todos.push({ text: $scope.newTodo, completed: false });
      $scope.newTodo = '';
    }
  };
  
  $scope.removeTodo = function(index) {
    $scope.todos.splice(index, 1);
  };
});

Controller As Syntax

app.controller('UserController', function() {
  this.name = 'John';
  this.greet = function() {
    return 'Hello, ' + this.name;
  };
});
<div ng-controller="UserController as user">
  <h1>{{user.name}}</h1>
  <p>{{user.greet()}}</p>
</div>

Best Practices

PracticeDescription
Don't manipulate DOMUse directives
Keep controllers thinUse services
Use controller asAvoid $scope
Single responsibilityOne controller per view

Mini Practice

  1. Create a controller
  2. Add methods and properties
  3. Use controller as syntax
  4. Follow best practices

Up Next

Continue with Scope — AngularJS scope.

Related Topics

Frequently Asked Questions about Controllers

What is Controllers in AngularJS?

Controllers is a fundamental concept in AngularJS. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn Controllers?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Controllers.

Why is Controllers important in AngularJS?

Controllers is essential for AngularJS development. Understanding this concept will help you write better code and solve real-world problems more effectively.