AngularJs Service-自定义服务

前端之家收集整理的这篇文章主要介绍了AngularJs Service-自定义服务前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

在AngularJs中 ,服务是一个函数或对象,可以在你的AngularJs 应用中使用

服务是注册在模块下的

实例1:

<div ng-app="myApp" ng-controller="myCtrl">
    <p>
        数字:{{number}}
    </p>
    <p>
        十六进制:<b>{{number2}}</b>
    </p>
    <p>
        十六进制2:<b>{{number|myFormat}}</b>
    </p>
</div>
<script>
    //在AngularJs中 ,服务是一个函数或对象,可以在你的AngularJs 应用中使用
    //在控制器、在过滤器等中都可以使用
    //AngularJS 内建了30 多个服务。
    //创建自定义服务
    var app = angular.module('myApp',[]);
    app.service('hexfay',function () {
        this.getHex = function (x) {
            return x.toString(16);
        }
    });
    //要是使用定义的服务,需要再定义控制器的时候独立添加
    app.value('number',10);
    app.controller('myCtrl',function ($scope,number,hexfay) {
        $scope.number = number;
        $scope.number2 = hexfay.getHex($scope.number);
    });
    //在过滤器中使用服务
    app.filter('myFormat',function (hexfay) {
        return function (input) {
            return hexfay.getHex(input);
        }
    });
</script>


实例2:

@H_403_17@ <div ng-app="myApp" ng-controller="myCtrl"> <p>数字:{{number}}</p> <p>结果:<b>{{number2}}</b></p> </div> <script> //创建自定义服务1 var app = angular.module('myApp',[]); app.service('addition',function () { this.add = function (x) { return x + 10; } }); //创建自定义服务2,调用服务1 app.service('multipli',function (addition) { this.getMulti = function (x) { x = addition.add(x); return x * 10; } }); //要是使用定义的服务,需要再定义控制器的时候独立添加 app.value('number',10); app.controller('myCtrl',multipli) { $scope.number = number; $scope.number2 = multipli.getMulti($scope.number); }); </script>

猜你在找的Angularjs相关文章