AngularJS eliminates the repetitive DOM manipulation that plagues vanilla JavaScript UIs. Once you understand the binding model, building interactive UIs becomes much less painful. These examples cover the core concepts you need to get productive.
1. One-Way vs Two-Way Binding
<!-- One-way: model โ view only -->
<div ng-app ng-init="name='Felix'">
Hello, <span ng-bind="name"></span>
</div>
<!-- Two-way: input changes update the model -->
<div ng-app ng-controller="MyCtrl">
<input ng-model="name" />
<p>Hello, {{name}}</p>
</div>
Use ng-bind instead of {{"{{"}}"{{"}}"}} in the main HTML to avoid a flash of uncompiled template on slow loads.
2. ng-repeat with Controllers
app.controller('ListCtrl', function($scope) {
$scope.items = [
{ name: 'Java', type: 'Language' },
{ name: 'Spring Boot', type: 'Framework' },
{ name: 'Kafka', type: 'Messaging' }
];
});
<ul ng-controller="ListCtrl">
<li ng-repeat="item in items">
{{item.name}} โ {{item.type}}
</li>
</ul>
3. DOM Directives
<!-- Show/hide based on model -->
<div ng-show="isLoggedIn">Welcome back!</div>
<div ng-hide="isLoggedIn">Please sign in.</div>
<!-- Disable a button conditionally -->
<button ng-disabled="form.$invalid">Submit</button>
4. Form Validation
<form name="myForm" novalidate>
<input name="email" type="email" ng-model="user.email" required />
<span ng-show="myForm.email.$dirty && myForm.email.$invalid">
Valid email required.
</span>
<button ng-disabled="myForm.$invalid">Submit</button>
</form>
Key properties: $dirty (user touched the field), $invalid (fails validation), $pristine (untouched). Show errors only after $dirty to avoid yelling at the user before they type anything.
5. Routing with ng-view
app.config(function($routeProvider) {
$routeProvider
.when('/home', { templateUrl: 'home.html', controller: 'HomeCtrl' })
.when('/about', { templateUrl: 'about.html', controller: 'AboutCtrl' })
.otherwise({ redirectTo: '/home' });
});
<!-- In index.html -->
<a href="#/home">Home</a> | <a href="#/about">About</a>
<div ng-view></div>
6. Factory vs Service
// Factory โ returns an object
app.factory('MathFactory', function() {
return {
square: function(n) { return n * n; }
};
});
// Service โ uses 'this'
app.service('MathService', function() {
this.square = function(n) { return n * n; };
});
Both are singletons in AngularJS โ the difference is how you define them, not how they behave. Factories feel more natural for functional patterns; services for class-style definitions.
7. Custom Directives
app.directive('highlight', function() {
return {
restrict: 'A',
link: function(scope, element, attrs) {
element.css('background', attrs.highlight || 'yellow');
}
};
});
<p highlight="cyan">This text has a cyan background.</p>
These basics cover 80% of what you need for real AngularJS work. The remaining 20% โ digest cycle, watchers, performance tuning โ comes with experience on larger apps.