0% found this document useful (0 votes)
8 views

AngularJS Chap 4

Uploaded by

priyanakrani21
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

AngularJS Chap 4

Uploaded by

priyanakrani21
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 18

AngularJS - Dependency Injection

Dependency Injection is a software design in which components are given


their dependencies instead of hard coding them within the component. It
relieves a component from locating the dependency and makes
dependencies configurable. It also helps in making components reusable,
maintainable and testable.

AngularJS provides a supreme Dependency Injection mechanism. It


provides following core components which can be injected into each other
as dependencies.

 Value
 Factory
 Service
 Provider
 Constant

Value

Value is a simple JavaScript object, which is required to pass values to the


controller during config phase (config phase is when AngularJS bootstraps
itself).

//define a module
var mainApp = angular.module("mainApp", []);

//create a value object as "defaultInput" and pass it a data.


mainApp.value("defaultInput", 5);
...

//inject the value in the controller using its name "defaultInput"


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);
}
});
Factory

Factory is a function which is used to return value. It creates a value on


demand whenever a service or a controller requires it. It generally uses a
factory function to calculate and return the value.

//define a module
var mainApp = angular.module("mainApp", []);

//create a factory "MathService" which provides a method multiply to return


multiplication of two numbers
mainApp.factory('MathService', function() {
var factory = {};

factory.multiply = function(a, b) {
return a * b
}
return factory;
});

//inject the factory "MathService" in a service to utilize the multiply


method of factory.
mainApp.service('CalcService', function(MathService) {
this.square = function(a) {
return MathService.multiply(a,a);
}
});
...

Explore our latest online courses and learn new skills at your own pace. Enroll and
become a certified expert to boost your career.

Service

Service is a singleton JavaScript object containing a set of functions to


perform certain tasks. Service is defined using service() function and it is
then injected into the controllers.

//define a module
var mainApp = angular.module("mainApp", []);
...

//create a service which defines a method square to return square of a number.


mainApp.service('CalcService', function(MathService) {
this.square = function(a) {
return MathService.multiply(a,a);
}
});

//inject the service "CalcService" into the controller


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);
}
});

Provider

Provider is used by AngularJS internally to create services, factory, etc.


during the config phase. The following script can be used to create
MathService that we created earlier. Provider is a special factory method
with get() method which is used to return the value/service/factory.

//define a module
var mainApp = angular.module("mainApp", []);
...

//create a service using provider which defines a method square to return


square of a number.
mainApp.config(function($provide) {
$provide.provider('MathService', function() {
this.$get = function() {
var factory = {};

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.

mainApp.constant("configParam", "constant value");

Example

The following example shows the use of all the above-mentioned


directives −

testAngularJS.htm
<html>
<head>
<title>AngularJS Dependency Injection</title>
</head>

<body>
<h2>AngularJS Sample Application</h2>

<div ng-app = "mainApp" ng-controller = "CalcController">


<p>Enter a number: <input type = "number" ng-model = "number"
/></p>
<button ng-click = "square()">X<sup>2</sup></button>
<p>Result: {{result}}</p>
</div>

<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

Open testAngularJS.htm in a web browser and see the result.


Dependency injection (DI) is a core feature of AngularJS that allows you to manage
and inject dependencies into your components (controllers, services, directives,
etc.). Here's how to use it:

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!';
};
});

 Factories: Similar to services, but provide more flexibility in creating objects.

JavaScript
angular.module('myApp').factory('MyFactory', function() {
return {
getData: function() {
return 'Hello from MyFactory!';
}
};
});

 Values and Constants: Inject simple values or constants.

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();
});

 In Services/Factories: Inject other dependencies into services/factories.

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
};
});

3. Minification Safe Injection:


 Use the array notation: To ensure your code works after minification, use the array notation to
inject dependencies.

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

Dependency injection in AngularJS provides several key advantages, including: easier


unit testing by allowing for mock dependencies, improved code maintainability and
readability, loose coupling between components, better code reusability, and simplified
application scaling; essentially making it easier to develop, test, and maintain complex
web applications by managing dependencies effectively.

Key benefits of dependency injection in AngularJS:


 Enhanced Testability:
Dependency injection allows developers to easily inject mock dependencies during testing,
making it simple to isolate and test individual components without relying on external services.
 Loose Coupling:
By injecting dependencies, components become less tightly coupled, meaning changes to one
component won't significantly impact other parts of the application.
 Code Reusability:
Services defined with dependency injection can be easily reused across different parts of the
application.

 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.

Injection Dependency in Service

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!";
};
});

Injecting the Service:


JavaScript
angular.module('myApp')
.controller('myController', function($scope, myService) {
$scope.message = myService.sayHello();
});

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.

Different Ways of Injecting:


1. Inline Array Notation (Minification Safe).
JavaScript
angular.module('myApp')
.controller('myController', ['$scope', 'myService', function($scope, myService) {
// ...
}]);
2. Implicit Annotation (Not Minification Safe).
JavaScript
angular.module('myApp')
.controller('myController', function($scope, myService) {
// ...
});

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:

 $routeProvider is used to configure the routes. It helps to define what page to


display when a user clicks a link.
 It accepts either when() or otherwise() method.
 The ngRoute must be added as a dependency in the application module:

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>

Example 2: This example describes the AngularJS Routing by the “Otherwise”


method is used with the “when” method, where the otherwise() method is used to set
the route definition to change the route when no route definition is matched

<!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:

 Create a config block for your app


 Configure a home state using $stateProvider and $urlRouterProvider
 Use otherwise() to redirect unspecified routes
 Use the 'stateProvider' method to create a route or a state in an application

What is the difference between ngRoute and ui-


router?
ngRoute: The ngRoute is a module that was developed by the AngularJS team which
was a part of AngularJS core earlier.

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

sections. multiple named-views, it helps


to inherit pages from other
sections.

In the ngRoute have to change all In the ui-router it allows strong-


the links manually that will be type linking between states so if
time-consuming for the larger you change any one place link
applications, but smaller that will change the links every
application nrRoute will perform where. That has to be used by ui-
faster. sref.

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

To get Params as a service in the To get Params as a service in the


ngRoute $route -> ui-router $state ->
$route.current.params.id and $rou $state.params.id and $statePara
teParams -> $routeParams.id ms -> $stateParams.id

The ngRoute organized around The ui-router organized around


ngRoute ui-router

the URL routes. states routes.

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:

<ANY class="ng-view [onload: string;] [autoscroll: string;]"> ... </ANY>

Arguments

Param Type Details

string Expression to evaluate whenever the view updates.


onload

(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

- If the attribute is set without value, enable scrolling.


- Otherwise enable scrolling only if the `autoscroll` attribute value evalu
as an expression yields a truthy value.

Events
 $viewContentLoaded
Emitted every time the ngView content is reloaded.

Type:

emit

Target:

the current ngView scope

Animations
Animation Occurs

enter when the new element is inserted to the DOM

leave when the old element is removed from to the DOM

The enter and leave animation occur concurrently.


Click here to learn more about the steps involved in the animation.

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
*/

You might also like