AngularJS gets a bad reputation these days โ it's been superseded by Angular 2+ and React. But understanding it properly is still valuable: the concepts of two-way binding, dependency injection and the MVC pattern translate directly to every modern framework. And in 2016, it was the dominant choice for Java backends with a JavaScript frontend.
Prerequisites: basic JavaScript, understanding of MVC, HTML and CSS. That's it.
Part 1: One-Way Binding
<div ng-app ng-init="firstName='Felix'; lastName='Abdullaev'">
<!-- Curly braces syntax -->
<p>{{firstName}} {{lastName}}</p>
<!-- ng-bind avoids flash of {{}} on slow loads -->
<p><span ng-bind="firstName"></span></p>
</div>
One-way means data flows from model โ view. Changing the model updates the view. The view can't push changes back to the model.
Part 2: Two-Way Binding
<div ng-app ng-controller="PersonCtrl">
First: <input ng-model="person.first" />
Last: <input ng-model="person.last" />
<p>Hello, {{person.first}} {{person.last}}</p>
</div>
ng-model creates two-way binding โ typing in the input immediately updates the displayed value. No event listeners, no DOM queries. This is the AngularJS core value proposition.
Part 3: Modules, Controllers & Directives
var app = angular.module('MyApp', []);
app.controller('PersonCtrl', function($scope) {
$scope.person = { first: 'Felix', last: 'Abdullaev' };
$scope.greet = function() {
return 'Hello, ' + $scope.person.first;
};
});
<!-- ng-repeat -->
<ul ng-controller="ListCtrl">
<li ng-repeat="item in items" ng-class="{active: item.selected}">
{{item.name}}
</li>
</ul>
Think of modules as Java packages โ they organise code and manage dependencies. Controllers own the logic for a specific view. Directives extend HTML with custom behaviour.
Part 4: Form Elements
<!-- Checkbox -->
<input type="checkbox" ng-model="user.subscribed" ng-true-value="'yes'" ng-false-value="'no'" />
<!-- Radio -->
<input type="radio" ng-model="user.role" value="admin" /> Admin
<input type="radio" ng-model="user.role" value="viewer" /> Viewer
<!-- Select from array -->
<select ng-model="user.country" ng-options="c for c in countries"></select>
Part 5: Controllers vs Services
This is the most important conceptual distinction for building maintainable AngularJS apps.
| Controllers | Services |
|---|---|
| Presentation logic | Business logic |
| View-specific | Reusable across the whole app |
| Re-created when view changes | Singleton โ live for app lifetime |
| Own $scope variables | Stateful, shared state |
app.service('UserService', function($http) {
var cache = null;
this.getUser = function(id) {
if (cache) return Promise.resolve(cache);
return $http.get('/api/users/' + id).then(function(res) {
cache = res.data;
return cache;
});
};
});
app.controller('ProfileCtrl', function($scope, UserService) {
UserService.getUser(1).then(function(user) {
$scope.user = user;
});
});