溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

angularJs在多個控制器中共享服務(wù)數(shù)據(jù)的方法

發(fā)布時間:2020-10-19 06:20:15 來源:腳本之家 閱讀:129 作者:泠泠在路上 欄目:web開發(fā)

如下所示:

<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', []);
 //定義服務(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在多個控制器中共享服務(wù)數(shù)據(jù)的方法就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持億速云。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI