在angularjs中,我们可以自定义自己的service。可以说得是自定义的方法,函数。

下面我们一步一步来演示吧:
首先为angularjs定义一个app:
Angularjs演示Service功能_ng-controller


Angularjs演示Service功能_Service_02Angularjs演示Service功能_Service_03
var demoApp = angular.module('demoApp', []);
Source Code

 

demoApp名称即是我们定义好的app。下面是本篇的重点,定义一个service:
Angularjs演示Service功能_ng-app_04

 

Angularjs演示Service功能_Service_02Angularjs演示Service功能_Service_03
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;
    }
});
Source Code

 

angularjs还差一个控制器:
Angularjs演示Service功能_function_07

 

Angularjs演示Service功能_Service_02Angularjs演示Service功能_Service_03
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);
});
Source Code

 
最后ASP.NET MVC 视图的实现:
Angularjs演示Service功能_ng-app_10

 

程序运行得到的结果:
Angularjs演示Service功能_ng-app_11