温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

angularJs在多个控制器中共享服务数据的方法

发布时间:2020-10-19 06:20:15 来源:脚本之家 阅读:116 作者:泠泠在路上 栏目:web开发

如下所示:

<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>
  <h2>{{web.name}}</h2>
  <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在多个控制器中共享服务数据的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持亿速云。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI