Services in Angular JS

2 篇文章 0 订阅
1 篇文章 0 订阅

Angular提供了三种服务:factory、service和provider。

下面的代码放入 /path/to/tomcat/webapp,
(1)Windows进入/path/to/tomcat/bin,运行startup.bat,如果配置了环境变量CATALINA_HOME,直接cmd执行startup.bat即可;
(2)Linux进入/path/to/tomcat/bin,执行./startup.sh。
输入url:localhost:8080/your_path/xxx.html即可运行。

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>AngularJS 中的 factory、 service 和 provider</title>
    <script src="js/angular.min.js"></script>
    <script type="text/javascript">
        var app = angular.module('MyApp', []);

        app.factory('MyFactory', function() {
            // define result object of factory.
            var result = {};
            // add some property and method to the object
            result.greeting = 'Hello from factory.';
            // return the object;
            return result;
        });

        app.service('MyService', function() {
            this.greeting = 'Hello from service';
        });

        app.provider('MyProvider', function() {
            // default name is 'anonymous';
            var defaultName = 'anonymous';
            var name = defaultName;
            // setName can be called duaring module init
            this.setName = function(newName) {
                name = newName;
            }

            this.$get = function() {
                var result = {};
                result.greeting = 'Hello from provider';

                result.name = name;
                result.defaultName = defaultName;
                return result;
            }

        })

        app.controller('TestController', ['$scope', 'MyFactory', 'MyService', 'MyProvider', function($scope, myFactory, myService, myProvider) {
            $scope.greetingFromFactory = myFactory.greeting;
            $scope.greetingFromService = myService.greeting;
            $scope.greetingFromProvider = myProvider.greeting;

            $scope.defaultName = myProvider.defaultName;
            $scope.name = myProvider.name
        }]);

        app.config(function(MyProviderProvider) {
            MyProviderProvider.setName('Angularjs Provider');
        });
    </script>
</head>
<body ng-app="MyApp" ng-controller="TestController">
    <p>greeting from factory:  {{greetingFromFactory}}</p>
    <p>greeting from service:  {{greetingFromService}}</p>
    <p>greeting from provider: {{greetingFromProvider}}</p>
    <p>defaultName: {{defaultName}}, config to: {{name}}</p>
</body>
</html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值