AngularJs之自定义服务实现多个控制器之间的数据共享

AngularJs之自定义服务实现多个控制器之间的数据共享,在同一页面当中,多处用到同一个数据,一般情况下我们需要重复写很多次代码,但是使用Angular提供的自定义服务,可以只写一次代码,提供给很多模块和控制器使用,这样可以减少代码沉兑。具体代码如下:

html部分:

01<body ng-app="app">
02    <div ng-controller="ctr1">
03        <table cellpadding="0" cellspacing="0">
04            <thead>
05                <tr>
06                    <td>网站名称</td>
07                    <td>网站地址</td>
08                </tr>
09            </thead>
10            <tbody>
11                <tr ng-repeat="(key, value) in data">
12                    <td>{{value.webname}}</td>
13                    <td>{{value.weburl}}</td>
14                </tr>
15            </tbody>
16        </table>
17    </div>
18    <hr />
19    <div ng-controller="ctr2">
20        <table cellpadding="0" cellspacing="0">
21            <thead>
22            <tr>
23                <td>网站名称</td>
24                <td>网站地址</td>
25            </tr>
26            </thead>
27            <tbody>
28            <tr ng-repeat="(key, value) in data">
29                <td>{{value.webname}}</td>
30                <td>{{value.weburl}}</td>
31            </tr>
32            </tbody>
33        </table>
34    </div>
35</body>

JavaScript部分:

01var m = angular.module('app', []);
02m.factory('zymBlog', ['$http'function($http){
03    return {
04        'get' function(){
05            return $http({
06                'url' './1.php',
07                'method' 'post',
08            }).then(function(result){
09                return result.data;
10            });
11        }
12    }
13}]);
14m.controller('ctr1', ['$scope''zymBlog'function($scope, zymBlog){
15    zymBlog.get().then(function(result){
16        $scope.data = result;
17    });
18}]);
19m.controller('ctr2', ['$scope''zymBlog'function($scope, zymBlog){
20    zymBlog.get().then(function(result){
21        $scope.data = result;
22    });
23}]);

以上,使用factory自定义服务,第一个参数是服务名称,第二个参数是数组,包含需要依赖注入的其他服务,通过这个自定义服务获取到数据,其他的控制器都可以进行使用!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值