如下所示:
<div ng-app="module"> <div ng-controller="ctrl1"> <table border="1" width="600"> <tr> <td>網(wǎ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)站名稱</td> <td>網(wǎng)址</td> </tr> <tr ng-repeat="v in data.webs"> <td>{{v.name}}</td> <td>{{v.url}}</td> </tr> </table> <h2>{{web.name}}</h2> <button ng-click="removeAll()">刪除所有數(shù)據(jù)</button> </div> </div> <script> var m = angular.module('module', []); //定義服務 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>
分享題目:angularJs在多個控制器中共享服務數(shù)據(jù)的方法-創(chuàng)新互聯(lián)
本文鏈接:http://jinyejixie.com/article42/coedec.html
成都網(wǎng)站建設公司_創(chuàng)新互聯(lián),為您提供做網(wǎng)站、定制開發(fā)、電子商務、網(wǎng)站收錄、搜索引擎優(yōu)化、手機網(wǎng)站建設
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)