Although AngularJS (the original JavaScript-based framework) is legacy, many enterprise and legacy apps still run on it. Knowing the most useful snippets helps developers maintain and extend applications efficiently.
Component & Template Basics
1. Defining a Module
var app = angular.module('myApp', []);
2. Creating a Controller
app.controller('MainCtrl', function($scope) {
$scope.title = "Hello AngularJS";
});
3. Interpolation in Templates
<p>{{ title }}</p>
4. ng-bind Usage
<p ng-bind="title"></p>
5. Two-Way Data Binding
<input type="text" ng-model="name" />
<p>Hello {{ name }}</p>
Directives & Structural Logic
6. ng-if Example
<p ng-if="isVisible">This is visible</p>
7. ng-show / ng-hide Usage
<p ng-show="showText">Shown Content</p>
<p ng-hide="hideText">Hidden Content</p>
8. ng-repeat Example
<ul>
<li ng-repeat="item in items">{{ item }}</li>
</ul>
9. ng-switch Usage
<div ng-switch="value">
<div ng-switch-when="a">A</div>
<div ng-switch-when="b">B</div>
<div ng-switch-default>Other</div>
</div>
10. Creating a Custom Directive
app.directive('myDirective', function() {
return {
template: '<p>This is my directive</p>'
};
});
Services & Dependency Injection
11. Creating a Service
app.service('MyService', function() {
this.sayHello = function() {
return "Hello from service";
};
});
12. Using a Factory
app.factory('DataFactory', function() {
var data = { message: "Shared Data" };
return { get: () => data };
});
13. Using a Provider
app.provider('Config', function() {
this.$get = function() {
return { apiUrl: '/api/v1' };
};
});
14. Injecting a Service in a Controller
app.controller('TestCtrl', function($scope, MyService) {
$scope.greeting = MyService.sayHello();
});
15. \$http GET Request
$http.get('/api/data').then(function(response) {
$scope.data = response.data;
});
Forms & Validation
16. ng-model Example
<input type="text" ng-model="username" />
<p>You typed: {{ username }}</p>
17. Simple Form with ng-submit
<form ng-submit="submitForm()">
<input ng-model="user.email" required />
<button type="submit">Submit</button>
</form>
18. Validating Form Field
<input type="email" ng-model="user.email" required />
<span ng-show="myForm.email.$error.required">Email is required!</span>
19. \$dirty and \$pristine Example
<input type="text" ng-model="name" />
<p ng-show="myForm.name.$dirty">Field changed</p>
20. Disable Button based on Validation
<button ng-disabled="myForm.$invalid">Submit</button>
Filters & Pipes
21. Using Built-in Currency Filter
<p>{{ price | currency:'USD$' }}</p>
22. Date Filter
<p>{{ today | date:'fullDate' }}</p>
23. Custom Filter Example
app.filter('reverse', function() {
return function(input) {
return input.split('').reverse().join('');
};
});
24. Limit To Filter
<p>{{ longText | limitTo:50 }}</p>
25. OrderBy Filter
<li ng-repeat="item in items | orderBy:'name'">{{ item.name }}</li>
Routing (ngRoute)
26. Configuring Routes
app.config(function($routeProvider) {
$routeProvider
.when('/home', { templateUrl: 'home.html', controller: 'HomeCtrl' })
.otherwise({ redirectTo: '/home' });
});
27. Navigating with ng-href
<a ng-href="#!/home">Go Home</a>
28. Getting Route Params
app.controller('DetailCtrl', function($routeParams) {
console.log($routeParams.id);
});
29. ng-view Placeholder
<div ng-view></div>
30. Default Route Handling
$routeProvider.otherwise({ template: '<h1>Not Found</h1>' });
Scope & Data Binding
31. \$watch Example
$scope.$watch('name', function(newVal, oldVal) {
console.log('Name changed:', newVal);
});
32. \$apply Example
$scope.$apply(function() {
$scope.value = "Updated";
});
33. Isolate Scope in Directive
app.directive('userCard', function() {
return {
scope: { user: '=' },
template: '<p>{{ user.name }}</p>'
};
});
34. Two-Way Binding in Directive
scope: { data: '=' }
35. One-Way Binding in Directive
scope: { label: '@' }
Events & Communication
36. ng-click Example
<button ng-click="sayHello()">Click</button>
37. \$emit Example
$scope.$emit('customEvent', { data: 123 });
38. \$broadcast Example
$scope.$broadcast('childEvent', { msg: "Hello" });
39. \$on Example
$scope.$on('customEvent', function(event, args) {
$scope.received = args.data;
});
40. ng-change Example
<input ng-model="value" ng-change="changed()" />
Performance & Utilities
41. Track by \$index
<li ng-repeat="item in items track by $index">{{ item }}</li>
42. One-Time Binding
<p>{{::username}}</p>
43. ng-cloak Example
<p ng-cloak>{{ title }}</p>
44. Debouncing Inputs
<input ng-model="search" ng-model-options="{ debounce: 500 }" />
45. Limit Re-render with track by id
<li ng-repeat="user in users track by user.id">{{ user.name }}</li>
Advanced AngularJS
46. \$timeout Example
$timeout(function() {
$scope.message = "Updated after delay";
}, 2000);
47. \$interval Example
$interval(function() {
$scope.counter++;
}, 1000);
48. \$q Promise Example
var deferred = $q.defer();
$http.get('/api').then(deferred.resolve, deferred.reject);
return deferred.promise;
49. ng-include Example
<div ng-include="'template.html'"></div>
50. Constant and Value Example
app.constant('API_URL', '/api/');
app.value('version', '1.0.0');
Top comments (0)