angularJs在多個控制器中共享服務數據的方法

今天小編就爲大家分享一篇angularJs在多個控制器中共享服務數據的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧

如下所示:

<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

<?php
$data = [
 [ 'name' => '百度', 'url' => 'www.baidu.com' ],
 [ 'name' => '谷歌', 'url' => 'google.com' ],
];
echo json_encode($data,JSON_UNESCAPED_UNICODE);

以上這篇angularJs在多個控制器中共享服務數據的方法就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持神馬文庫。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章