AngularJS Chap 4
AngularJS Chap 4
Value
Factory
Service
Provider
Constant
Value
//define a module
var mainApp = angular.module("mainApp", []);
$scope.square = function() {
$scope.result = CalcService.square($scope.number);
}
});
Factory
//define a module
var mainApp = angular.module("mainApp", []);
factory.multiply = function(a, b) {
return a * b
}
return factory;
});
Explore our latest online courses and learn new skills at your own pace. Enroll and
become a certified expert to boost your career.
Service
//define a module
var mainApp = angular.module("mainApp", []);
...
Provider
//define a module
var mainApp = angular.module("mainApp", []);
...
factory.multiply = function(a, b) {
return a * b;
}
return factory;
};
});
});
Constant
Constants are used to pass values at the config phase considering the
fact that value cannot be used during the config phase.
Example
testAngularJS.htm
<html>
<head>
<title>AngularJS Dependency Injection</title>
</head>
<body>
<h2>AngularJS Sample Application</h2>
<script src =
"https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js">
</script>
<script>
var mainApp = angular.module("mainApp", []);
mainApp.config(function($provide) {
$provide.provider('MathService', function() {
this.$get = function() {
var factory = {};
factory.multiply = function(a, b) {
return a * b;
}
return factory;
};
});
});
mainApp.value("defaultInput", 5);
mainApp.factory('MathService', function() {
var factory = {};
factory.multiply = function(a, b) {
return a * b;
}
return factory;
});
mainApp.service('CalcService', function(MathService) {
this.square = function(a) {
return MathService.multiply(a,a);
}
});
mainApp.controller('CalcController', function($scope, CalcService,
defaultInput) {
$scope.number = defaultInput;
$scope.result = CalcService.square($scope.number);
$scope.square = function() {
$scope.result = CalcService.square($scope.number);
}
});
</script>
</body>
</html>
Output
1. Defining Dependencies:
Services: Create services to encapsulate reusable logic and data.
JavaScript
angular.module('myApp').service('MyService', function() {
this.getData = function() {
return 'Hello from MyService!';
};
});
JavaScript
angular.module('myApp').factory('MyFactory', function() {
return {
getData: function() {
return 'Hello from MyFactory!';
}
};
});
JavaScript
angular.module('myApp').value('API_URL', 'https://api.example.com');
2. Injecting Dependencies:
In Controllers: Inject dependencies into controllers using the array notation.
JavaScript
angular.module('myApp').controller('MyController', function($scope,
MyService) {
$scope.data = MyService.getData();
});
JavaScript
angular.module('myApp').service('MyService', function($http, API_URL) {
this.getData = function() {
return $http.get(API_URL + '/data');
};
});
In Directives: Inject dependencies into directives.
JavaScript
angular.module('myApp').directive('myDirective', function(MyService) {
return {
// ... directive definition
};
});
JavaScript
angular.module('myApp').controller('MyController', ['$scope',
'MyService', function($scope, MyService) {
// ... controller logic
}]);
Benefits of DI:
Modularity: DI promotes modularity by decoupling components.
Testability: Easier to write unit tests by injecting mock dependencies.
Maintainability: Code becomes more organized and easier to maintain
Improved Maintainability:
Code becomes more modular and easier to understand due to clear dependency relationships.
Simplified Application Scaling:
As the application grows, managing dependencies becomes easier with dependency injection.
Reduced Boilerplate Code:
By handling dependency creation through the framework, developers don't need to write
repetitive code for dependency management.
Better Architecture:
Dependency injection promotes a cleaner application architecture by separating concerns and
promoting modularity.
Dependency Injection (DI) is a core feature of AngularJS that allows you to decouple
components by providing their dependencies from external sources rather than hardcoding them
within the component.
Here's how DI works in AngularJS services:
Creating a Service:
JavaScript
angular.module('myApp', [])
.service('myService', function() {
this.sayHello = function() {
return "Hello from myService!";
};
});
Explanation:
Service Definition:
The myService is defined using the service() method. It's a simple function that provides
a sayHello method.
Injection:
In the controller, the myService is specified as a dependency in the controller's function
arguments. AngularJS's DI system takes care of providing the myService instance to the
controller.
Benefits of DI:
Modularity: Services can be reused across different components, promoting code
reusability.
Testability: Components can be easily unit tested by injecting mock services.
Maintainability: Code is easier to understand and modify as dependencies are managed by
the framework.
Overview of Routing :
In AngularJS, routing enables you to create Single-Page Applications (SPAs) where the
content dynamically changes without full page reloads. Here's an overview:
Key Components:
ngRoute Module: The core module that provides routing capabilities.
$routeProvider: A service used to configure routes.
$routeParams: A service that provides access to route parameters.
ng-view Directive: A directive that marks the area where the view associated with the current
route is rendered.
Defining Routes: You define routes using $routeProvider, associating URL patterns with
corresponding views and controllers:
Routing in AngularJS is used when the user wants to navigate to different pages in
an application but still wants it to be a single-page application. AngularJS routes
enable the user to create different URLs for different content in an application.
The ngRoute module helps in accessing different pages of an application without
reloading the entire application.
AngularJS also provides the ability to pass parameters in routes, which means, it
allows us to dynamically generate routes and handle different data based on the
parameters. We can define route patterns with placeholders for parameters, and
AngularJS will extract the values from the URL and make them available in your
controller. This parameterization of routes can be useful for creating dynamic pages
or handling specific data queries within a single-page application.
Important:
Example 1: This example describes the AngularJS Routing by implementing the “when”
method that specifies the new route definition to the $route service.
HTML
<!DOCTYPE html>
<html>
<head>
<script src=
"https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js ">
</script>
<script src=
"https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular-route.js ">
</script>
</head>
<body ng-app="myApp">
<p>
<a href="#/!">
<img src=
"https://media.geeksforgeeks.org/wp-content/uploads/20190221234751/
geeksforgeeks-logo1.png "
alt="GeeksforGeeks"
style="width: 90vw;">
</a>
</p>
<a href="#!courses">Courses@geeksforgeeks</a>
<br>
<a href="#!internships">Internships@geeksforgeeks</a>
<div ng-view></div>
<script>
const app = angular.module("myApp", ["ngRoute"]);
app.config(function ($routeProvider) {
$routeProvider
.when("/", {
template: `<h1>Welcome to GeeksForGeeks</h1>
<p>
Click on the links to change this content
</p>`
})
.when("/courses", {
template: `<h1>Courses Offered</h1>
<p>
<ul>
<li>Machine Learning Foundation</li>
<li>Geeks Classes</li>
<li>System Design</li>
</ul>
</p>`
})
.when("/internships", {
template: `<h1>Hire With Us</h1>
<p>
<ul>
<li>Software Developer</li>
<li>Technical Content Writer</li>
<li>Technical Content Engineer</li>
</ul>
</p>`
});
});
</script>
</body>
<!DOCTYPE html>
<html>
<head>
<script src=
"https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js">
</script>
<script src=
"https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular-route.js">
</script>
</head>
<body ng-app="myApp">
<p>
<a href="#/!">
<img src=
"https://media.geeksforgeeks.org/wp-content/uploads/20190221234751/
geeksforgeeks-logo1.png"
alt="GeeksForGeeks"
style="width: 90vw;">
</a>
</p>
<a href="#!courses">Courses@geeksforgeeks</a>
<br>
<a href="#!internships">Internships@geeksforgeeks</a>
<div ng-view></div>
<script>
const app = angular.module("myApp", ["ngRoute"]);
app.config(function ($routeProvider) {
$routeProvider
.when("/courses", {
template: `<h1>Courses Offered</h1>
<p>
<ul>
<li>Machine Learning Foundation</li>
<li>Geeks Classes</li>
<li>System Design</li>
</ul>
</p>`
})
.when("/internships", {
template: `<h1>Hire With Us</h1>
<p>
<ul>
<li>Software Developer</li>
<li>Technical Content Writer</li>
<li>Technical Content Engineer</li>
</ul>
</p>`
})
.otherwise({
template: `<h1>Please Select Something!</h1>
<p>
Nothing has been selected yet
</p>`
});
});
</script>
</body>
</html>
ngRoute
To use ngRoute for routing in AngularJS, you can:
Include the AngularJS Route module
Add ngRoute as a dependency in the application module
Use the $routeProvider to configure routes, such as defining which page to display when a
user clicks a link
Use the TemplateUrl property in the $routeProvider.when method
UI-Router
UI-Router is a client-side routing framework for AngularJS that allows users to navigate
between pages and views in a user-friendly way. UI-Router uses a state machine to
manage transitions between application states. To use UI-Router for routing in
AngularJS, you can:
This is a module so that will manage the basic scenarios better, less complexity
handles much better.
ui-router: The ui-router is a framework that was made outside of the AngularJS
project to enhance and improve the routing capabilities.
This is a framework so it will help you to organize parts of your project’s interface
Both of them has unique capabilities, choosing between them depends on your
projects.
You have to know which one is more useful to your working project, below the
features of both is provided that will clear your thoughts, which one should you
choose for your project.
ngRoute ui-router
The ngRoutr is good for smaller The ui-router is effective for the
app where you do not need to larger application because it
inherit the pages from other allows nested-views and
ngRoute ui-router
The router provider for the The router provider for the
ngRoute $routeProvider ngRoute $stateProvider $urlRout
erProvide
The template view for the ngRoute The template view for the ui-
is ng-view which is better compare router ui-view much powerful for
to ui-view. multipage inherit from other
sections.
You can’t determine if you are in You can easily determine if you
state. are in a state or parent of a state
to adjust UI element within your
templates via $state provided by
ui-router which you can expose
via setting it in $rootScope on
run.
The router start event for the The router start event for the
ngRoute $routeChangeStart ngRoute $stateChangeStart
Ng-view Directive :
The ng-view directive in AngularJS is used to dynamically inject the content of a view
into the main layout of your application. It's a core part of the ngRoute module, which
enables client-side routing in AngularJS applications.
How it works:
ngRoute Module: You need to include the ngRoute module in your application.
ng-view Directive: Add the ng-view directive in your main HTML template
(usually index.html). This acts as a placeholder for the views.
Route Configuration: Configure your routes using the $routeProvider service. Each route defines
a URL pattern and the corresponding view template to load.
Example:
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<title>AngularJS Routing</title>
<script src="angular.min.js"></script>
<script src="angular-route.min.js"></script>
<script src="app.js"></script>
</head>
<body>
<div ng-view></div>
</body>
</html>
// app.js
angular.module('myApp', ['ngRoute'])
.config(function($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'home.html',
controller: 'HomeController'
})
.when('/about', {
templateUrl: 'about.html',
controller: 'AboutController'
})
.otherwise({
redirectTo: '/'
});
});
Important Points:
Single Page Application (SPA): ng-view enables SPAs, where only the content within the ng-
view container changes, without reloading the entire page.
$routeProvider: This service is used to define the routes and their corresponding views.
templateUrl: Specifies the URL of the HTML template to load for the route.
controller: Specifies the controller to associate with the view.
otherwise: Defines a default route if no other route matches the current URL.
Note: AngularJS is no longer actively developed, and Angular (versions 2+) is the
recommended framework for modern web development. Angular uses a different
routing mechanism based on the RouterModule.
Overview of ngView
ngView is a directive that complements the $route service by including the rendered template
of the current route into the main layout ( index.html) file. Every time the current route
changes, the included view changes with it according to the configuration of
the $route service.
Requires the ngRoute module to be installed.
Directive Info
This directive creates new scope.
This directive executes at priority level 400.
Usage
as element:
<ng-view
[onload="string"]
[autoscroll="string"]>
...
</ng-view>
as attribute:
<ANY
ng-view
[onload="string"]
[autoscroll="string"]>
...
</ANY>
as CSS class:
Arguments
(optional)
autoscroll string Whether ngView should call $anchorScroll to scroll the viewport after the view is updated.
(optional) - If the attribute is not set, disable scrolling.
Param Type Details
Events
$viewContentLoaded
Emitted every time the ngView content is reloaded.
Type:
emit
Target:
Animations
Animation Occurs
Animations.css
.view-animate-container {
position: relative;
height: 100px !important;
background: white;
border: 1px solid black;
height: 40px;
overflow: hidden;
}
.view-animate {
padding: 10px;
}
.view-animate.ng-enter,
.view-animate.ng-leave {
transition: all cubic-bezier(0.25, 0.46, 0.45, 0.94) 1.5s;
display: block;
width: 100%;
border-left: 1px solid black;
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
padding: 10px;
}
.view-animate.ng-enter {
left: 100%;
}
.view-animate.ng-enter.ng-enter-active {
left: 0;
}
.view-animate.ng-leave.ng-leave-active {
left: -100%;
}
/*
Copyright 2024 Google LLC. All Rights Reserved.
Use of this source code is governed by an MIT-style license that
can be found in the LICENSE file at http://angular.io/license
*/