在angularjs中,我们可以自定义自己的service。可以说得是自定义的方法,函数。
下面我们一步一步来演示吧:
首先为angularjs定义一个app:
var demoApp = angular.module('demoApp', []);
demoApp名称即是我们定义好的app。下面是本篇的重点,定义一个service:
demoApp.service('calcService', function () { this.Addition = function (num1, num2) { return num1 + num2; } this.Substruction = function (num1, num2) { return num1 - num2; } this.Multiplication = function(num1, num2) { return num1 * num2; } this.Division = function (num1,num2) { return num1 / num2; } });
demoApp.controller('demoController', function ($scope, calcService) { $scope.result1 = calcService.Addition(12, 4); $scope.result2 = calcService.Substruction(14, 3); $scope.result3 = calcService.Multiplication(7, 9); $scope.result4 = calcService.Division(15, 3); });