[wp_ad_camp_5]
This post demonstrates how to use services from another module.
Contents
Software Requirements
- Windows 10
- Notepad++ or Brackets
- AngularJS 1.6.2
- Main HTML must be HTML5-compliant (optional)
Angular Modules
You SPA applications may be broken down into several modules. Each module contain related codes. Note that, ideally, there should only be one main module whose name is used with data-ng-app
directive.
Below is our myapp.js
. It has two (2) modules – myapp.util
and myapp
.
myapp
is your main module and it needs to use the calc
service from myapp.util
.
[wp_ad_camp_4]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | (function() { // An angular module angular.module('myapp.util',[]).factory('calc', [function(){ return { add: function(a, b) { return a + b; }, sub: function(a, b) { return a - b; }, div: function(a, b) { return a / b; }, mul: function(a, b) { return a * b; } }; }]) // Instantiate our main module and pass 'myapp.util' module var myapp = angular.module('myapp', ['myapp.util']); myapp.controller('mainController', ['$scope', 'calc', function($scope, calc) { $scope.a = 10; $scope.b = 14; var a = $scope.a; var b = $scope.b; $scope.sum = calc.add(a, b); $scope.diff = calc.sub(a, b); $scope.dividend = calc.div(a, b); $scope.product = calc.mul(a, b); }]); })(); |
[wp_ad_camp_2]
Main page
Our main page is a simple HTML file that shows the sum
, difference
, dividend
, and product
of 10 and 14.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | <!DOCTYPE html> <html lang="en" data-ng-app="myapp"> <head> <meta charset="utf-8"> <title>Use service from another module</title> <meta name="description" content="Use service from another module"> <script src="js/angular.min.js"></script> <script src="js/myapp.js"></script> </head> <body> <div style="border-style: dotted" data-ng-controller="mainController"> <h1>a = {{a}} and b = {{b}}</h1> <ul> <li>{{a}} + {{b}} = {{sum}}</li> <li>{{a}} / {{b}} = {{dividend}}</li> <li>{{a}} * {{b}} = {{product}}</li> <li>{{a}} - {{b}} = {{diff}}</li> </ul> </div> </body> </html> |
[wp_ad_camp_3]
Sample Output
Download the codes
[wp_ad_camp_1]
https://github.com/Turreta/AngularJS-use-service-from-another-module