Angular Js
Angular Js
1. What is AngularJS?
AngularJS is an open-source JavaScript framework developed by Google to build
dynamic, single-page web applications (SPAs).
Example:
htmlCopy code
<div ng-app="myApp">
<input type="text" ng-model="name">
<p>Hello, {{ name }}</p>
</div>
Example:
htmlCopy code
<!DOCTYPE html>
<html ng-app="myApp">
<!-- ... -->
</html>
Example:
Example:
htmlCopy code
<div ng-app="myApp">
<p>{{ 2 + 2 }}</p>
</div>
Example:
jsCopy code
var app = angular.module('myApp', []);
Example:
jsCopy code
app.controller('MyController', ['$scope', function($scope) {
// Controller logic here
}]);
Example:
htmlCopy code
<div ng-app="myApp">
<ul>
<li ng-repeat="item in items">{{ item }}</li>
</ul>
</div>
Example:
jsCopy code
app.controller('MyController', ['$http', function($http) {
$http.get('/api/data')
.then(function(response) {
// Process the response data
})
.catch(function(error) {
// Handle the error
});
}]);
Example:
htmlCopy code
<div ng-app="myApp">
<button ng-click="showMessage()">Click Me</button>
</div>
Example:
jsCopy code
app.service('MyService', function() {
this.sayHello = function(name) {
return "Hello, " + name + "!";
};
});
Example:
jsCopy code
app.controller('MyController', ['$scope', '$rootScope', function($scope, $rootScope) {
$rootScope.appTitle = "My App";
}]);
Example:
jsCopy code
app.directive('myDirective', function() {
return {
restrict: 'E',
template: '<p>This is my custom directive</p>'
};
});
Example:
htmlCopy code
<div ng-app="myApp">
<div ng-if="showElement">This will be shown if showElement is truthy.</div>
</div>
Example:
htmlCopy code
<div ng-view></div>
jsCopy code
app.config(function($routeProvider) {
$routeProvider
.when('/home', {
templateUrl: 'home.html',
controller: 'HomeController'
})
.when('/about', {
templateUrl: 'about.html',
controller: 'AboutController'
})
Example:
htmlCopy code
<div ng-app="myApp">
<p>{{ price | currency }}</p>
</div>
Example:
htmlCopy code
<div ng-app="myApp">
<input type="text" ng-model="name">
<p>Hello, {{ name }}</p>
</div>
Example:
htmlCopy code
<div ng-app="myApp">
<button ng-disabled="isDisabled">Click Me</button>
</div>
Example:
htmlCopy code
<div ng-app="myApp">
<form name="myForm" ng-submit="submitForm()">
<input type="text" name="username" ng-model="user.username" required>
<button type="submit">Submit</button>
</form>
</div>
jsCopy code
app.controller('MyController', ['$scope', function($scope) {
$scope.submitForm = function() {
if ($scope.myForm.$valid) {
// Form is valid, submit the data
}
};
}]);
Advanced Level:
Example:
jsCopy code
app.directive('myDirective', function() {
return {
restrict: 'E',
scope: {
message: '@'
},
template: '<p>{{ message }}</p>'
};
});
Example:
htmlCopy code
<div ng-app="myApp">
<div my-directive>
<p>This content will be transcluded into the directive template.</p>
</div>
</div>
jsCopy code
app.directive('myDirective', function() {
return {
restrict: 'A',
transclude: true,
template: '<div><p>Directive content:</p><div ng-transclude></div></div>'
};
});
Example:
jsCopy code
app.filter('reverse', function() {
htmlCopy code
<div ng-app="myApp">
<p>{{ 'Hello' | reverse }}</p>
</div>
Example:
jsCopy code
app.config(function($routeProvider, $locationProvider) {
$routeProvider
.when('/home', {
templateUrl: 'home.html',
controller: 'HomeController'
})
.when('/about', {
templateUrl: 'about.html',
controller: 'AboutController'
})
.otherwise({
redirectTo: '/home'
});
$locationProvider.html5Mode(true);
});
Example:
Example (Decorator for the $log service to prepend a timestamp to log messages):
jsCopy code
app.config(['$provide', function($provide) {
$provide.decorator('$log', ['$delegate', function($delegate) {
var originalLogFn = $delegate.log;
$delegate.log = function() {
var args = [].slice.call(arguments);
args[0] = new Date().toISOString() + ' - ' + args[0];
originalLogFn.apply(null, args);
};
return $delegate;
}]);
}]);
Example:
htmlCopy code
<div ng-app="myApp">
<p>Hello, {{ name }}</p>
</div>
Example:
jsCopy code
app.directive('myDirective', function() {
return {
restrict: 'E',
controller: function($scope) {
$scope.message = "Hello from directive controller";
},
template: '<p>{{ message }}</p>'
};
});
htmlCopy code
<my-directive></my-directive>
htmlCopy code
<div ng-app="myApp">
<form name="myForm">
<input type="email" name="email" ng-model="user.email" required>
<div ng-messages="myForm.email.$error">
<div ng-message="required">Email is required.</div>
<div ng-message="email">Invalid email address.</div>
</div>
</form>
</div>
34. What are the differences between one-way binding ({{ }}) and two-way binding
(ng-model)?
One-way binding ( {{ }} ) binds the data from the model to the view, while two-way
binding ( ng-model ) binds the data both from the model to the view and from the view
back to the model.
unsafe .
Example:
jsCopy code
app.config(['$httpProvider', function($httpProvider) {
$httpProvider.interceptors.push(function($q) {
return {
'responseError': function(rejection) {
// Handle the error globally
return $q.reject(rejection);
}
};
});
}]);
Example:
typescriptCopy code
interface IUser {
id: number;
name: string;
}
Example:
htmlCopy code
<div ng-app="myApp">
<ul>
jsCopy code
app.controller('MyController', ['$scope', function($scope) {
$scope.itemsPerPage = 5;
$scope.currentPage = 0;
$scope.items = [...]; // Your data array
$scope.prevPage = function() {
if ($scope.currentPage > 0) {
$scope.currentPage--;
}
};
$scope.nextPage = function() {
var lastPage = Math.ceil($scope.items.length / $scope.itemsPerPage) - 1;
if ($scope.currentPage < lastPage) {
$scope.currentPage++;
}
};
}]);
48. What are factories and services in AngularJS? How do they differ?
Both factories and services are used to create reusable components in AngularJS.
A factory is a function that returns an object or a function and is called only once, while
a service is a constructor function and is instantiated with the new keyword.
Example (Factory):
jsCopy code
app.factory('MyFactory', function() {
return {
// Factory logic here
};
});
Example (Service):
jsCopy code
app.service('MyService', function() {
// Service logic here
});
jsCopy code
app.controller('MyController', ['$scope', '$interval', function($scope, $interval) {
var intervalPromise = $interval(function() {
// Function to be executed at the interval
}, 1000);
$scope.stopInterval = function() {
$interval.cancel(intervalPromise);
};
}]);
Example:
jsCopy code
app.config(['$routeProvider', function($routeProvider) {
$routeProvider
.when('/items', {
templateUrl: 'items.html',
controller: 'ItemsController',
resolve: {
itemsData: function($http) {
return $http.get('/api/items').then(function(response) {
return response.data;
});
}
}
});
}]);
Example:
jsCopy code
app.controller('MyController', ['$scope', '$cookies', function($scope, $cookies) {
// Write a cookie
$cookies.put('username', 'John Doe');
// Read a cookie
var username = $cookies.get('username');
// Delete a cookie
$cookies.remove('username');
}]);
56. Explain the concept of the digest cycle and how it works in AngularJS.
The digest cycle is a loop in which AngularJS checks for changes in the model and
updates the view accordingly. It runs until all the watchers have been checked and
no changes are detected.
During the digest cycle, AngularJS compares the current model values with the previous
values and updates the bindings in the view if necessary. The digest cycle is triggered
by various events like user interactions, AJAX requests, timers, etc.
Performance: Angular is generally faster and more performant due to its optimized
rendering and change detection mechanisms.
Mobile Support: Angular has better support for mobile applications compared to
AngularJS.
Example:
jsCopy code
app.controller('MyController', ['$scope', '$http', function($scope, $http) {
$scope.uploadFile = function() {
var formData = new FormData();
formData.append('file', $scope.file);
$http.post('/api/upload', formData, {
transformRequest: angular.identity,
headers: { 'Content-Type': undefined }
})
.then(function(response) {
// File uploaded successfully
})
.catch(function(error) {
// Error uploading file
});
};
}]);
60. What are the best practices for organizing code in AngularJS applications?
Keep business logic in services and use controllers for view-related logic.
61. How to use third-party libraries that manipulate the DOM with AngularJS?
When using third-party libraries that manipulate the DOM directly, you should be
cautious to avoid conflicts with AngularJS's digest cycle. Make sure to use $apply or
$timeout to trigger the digest cycle after making changes with the library.
Example:
jsCopy code
app.controller('MyController', ['$scope', function($scope) {
$scope.$apply(function() {
// Call the third-party library's DOM manipulation code here
});
}]);
Example:
htmlCopy code
<div ng-app="myApp">
<img ng-src="{{ isVisible ? 'actual_image.jpg' : 'placeholder.jpg' }}" alt="Image">
</div>
jsCopy code
app.controller('MyController', ['$scope', function($scope) {
// Check if the image is in the viewport
$scope.isVisible = isImageVisibleInViewport();
function isImageVisibleInViewport() {
// Your logic to check if the image is visible in the viewport
}
Example:
jsCopy code
// app.config.js
var env = 'development'; // or 'production'
angular.module('myApp')
.constant('ENV', env)
.constant('API_BASE_URL', env === 'production' ? 'https://api.prod.com' : 'https://api.d
ev.com');
Example:
htmlCopy code
<div ng-app="myApp">
<div ng-class="{'highlight': isHighlighted, 'bold': isBold}">Content</div>
</div>
jsCopy code
app.controller('MyController', ['$scope', function($scope) {
$scope.isHighlighted = true;
$scope.isBold = false;
Example:
htmlCopy code
<div ng-app="myApp">
<input type="text" ng-model="searchText">
<ul>
<li ng-repeat="item in items | filter: searchText">{{ item }}</li>
</ul>
</div>