我是靠谱客的博主 糟糕白猫,这篇文章主要介绍angularJs在多个控制器中共享服务数据的方法,现在分享给大家,希望可以做个参考。

如下所示:

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
<div ng-app="module"> <div ng-controller="ctrl1"> <table border="1" width="600"> <tr> <td>网站名称</td> <td>网址</td> </tr> <tr ng-repeat="v in data.webs"> <td>{{v.name}}</td> <td>{{v.url}}</td> </tr> </table> </div> <hr> <div ng-controller="ctrl2"> <table border="1" width="600"> <tr> <td>网站名称</td> <td>网址</td> </tr> <tr ng-repeat="v in data.webs"> <td>{{v.name}}</td> <td>{{v.url}}</td> </tr> </table> <h1>{{web.name}}</h1> <button ng-click="removeAll()">删除所有数据</button> </div> </div> <script> var m = angular.module('module', []); //定义服务 m.factory('videoServer', ['$http', function ($http) { var obj = { data: {webs:[]}, //所有数据 all: function () { return $http({url: '1.php'}).then(function (response) { obj.data.webs = response.data; return obj.data; }); }, //获取一条数据 find: function (id) { return this.all().then(function (data) { for (var i = 0; i < data.length; i++) { if (data[i].id == id) { return data[i]; } } }); }, //删除所有数据 flush: function () { obj.data.webs=[]; } }; return obj; }]); //控制器ctrl1 m.controller('ctrl1', ['$scope', 'videoServer', function ($scope, videoServer) { videoServer.all().then(function (data) { $scope.data = data; }); }]); //控制器ctrl2 m.controller('ctrl2', ['$scope', 'videoServer', function ($scope, videoServer) { videoServer.all().then(function (data) { $scope.data = data; }); videoServer.find(1).then(function (data) { $scope.web = data; }) $scope.removeAll=function(){ videoServer.flush(); } }]); </script>

1.php

复制代码
1
2
3
4
5
6
<?php $data = [ [ 'name' => '百度', 'url' => 'www.baidu.com' ], [ 'name' => '谷歌', 'url' => 'google.com' ], ]; echo json_encode($data,JSON_UNESCAPED_UNICODE);

以上这篇angularJs在多个控制器中共享服务数据的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持靠谱客。

最后

以上就是糟糕白猫最近收集整理的关于angularJs在多个控制器中共享服务数据的方法的全部内容,更多相关angularJs在多个控制器中共享服务数据内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(161)

评论列表共有 0 条评论

立即
投稿
返回
顶部