angularJs在多個(gè)控制器中共享服務(wù)數(shù)據(jù)的方法
更新時(shí)間:2018年09月30日 10:50:03 作者:泠泠在路上
今天小編就為大家分享一篇angularJs在多個(gè)控制器中共享服務(wù)數(shù)據(jù)的方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧
如下所示:
<div ng-app="module">
<div ng-controller="ctrl1">
<table border="1" width="600">
<tr>
<td>網(wǎng)站名稱(chēng)</td>
<td>網(wǎng)址</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>網(wǎng)站名稱(chēng)</td>
<td>網(wǎng)址</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()">刪除所有數(shù)據(jù)</button>
</div>
</div>
<script>
var m = angular.module('module', []);
//定義服務(wù)
m.factory('videoServer', ['$http', function ($http) {
var obj = {
data: {webs:[]},
//所有數(shù)據(jù)
all: function () {
return $http({url: '1.php'}).then(function (response) {
obj.data.webs = response.data;
return obj.data;
});
},
//獲取一條數(shù)據(jù)
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];
}
}
});
},
//刪除所有數(shù)據(jù)
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
<?php $data = [ [ 'name' => '百度', 'url' => 'www.baidu.com' ], [ 'name' => '谷歌', 'url' => 'google.com' ], ]; echo json_encode($data,JSON_UNESCAPED_UNICODE);
以上這篇angularJs在多個(gè)控制器中共享服務(wù)數(shù)據(jù)的方法就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
詳解angularjs獲取元素以及angular.element()用法
本篇文章主要介紹了詳解angularjs獲取元素以及angular.element()用法 ,具有一定的參考價(jià)值,有興趣的可以了解一下2017-07-07
AngularJS動(dòng)態(tài)生成select下拉框的方法實(shí)例
這篇文章主要給大家介紹了關(guān)于AngularJS動(dòng)態(tài)生成select下拉框的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家學(xué)習(xí)或者使用AngularJS具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-11-11
Angular4學(xué)習(xí)筆記之根模塊與Ng模塊
這篇文章主要介紹了Angular4學(xué)習(xí)筆記之根模塊與Ng模塊,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2017-09-09
Angular中使用ng-zorro圖標(biāo)庫(kù)部分圖標(biāo)不能正常顯示問(wèn)題
這篇文章主要介紹了Angular中使用ng-zorro圖標(biāo)庫(kù)部分圖標(biāo)不能正常顯示問(wèn)題,非常不錯(cuò),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
2019-04-04
AngularJS 與Bootstrap實(shí)現(xiàn)表格分頁(yè)實(shí)例代碼
這篇文章主要介紹了AngularJS 與Bootstrap實(shí)現(xiàn)表格分頁(yè)的相關(guān)資料,并附實(shí)例代碼和實(shí)現(xiàn)效果圖,需要的朋友可以參考下
2016-10-10 
