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
| Practice | Description |
|---|---|
| Don't manipulate DOM | Use directives |
| Keep controllers thin | Use services |
| Use controller as | Avoid $scope |
| Single responsibility | One controller per view |
Mini Practice
- Create a controller
- Add methods and properties
- Use controller as syntax
- 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.