Prev Demo
AngularJS
>
Services
Next Demo
Write code here
J
|
B
|
A
<!DOCTYPE html> <html> <head> <title>Demo</title> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script> </head> <body> <h2>AngularJS Sample Service</h2> <div ng-app="myApp"> <div ng-controller="myController"> a = <input type="number" required ng-model="a" value="5" /> b = <input type="number" required ng-model="b" value="7" /> <button ng-click="Plus()">Add</button> <button ng-click="Minus()">Subtract</button> <p>The result is: <b>{{MathResult}}</b></p> </div> </div> <script> var myApp = angular.module('myApp', []) myApp.service('myService', function () { this.Sum = function (a, b) { return a + b; }; this.Subtract = function (a, b) { return a - b; }; }); myApp.controller('myController', function ($scope, myService) { $scope.Plus = function () { $scope.MathResult = myService.Sum($scope.a, $scope.b); }; $scope.Minus = function () { $scope.MathResult = myService.Subtract($scope.a, $scope.b); }; }); </script> </body> </html>
Note: We DO NOT save your trial code in our database.
Output