angularJs在多個(gè)控制器中共享服務(wù)數(shù)據(jù)的方法
如下所示:
<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)文章
理解Angular的providers給Http添加默認(rèn)headers
本篇文章主要介紹了理解Angular的providers給Http添加默認(rèn)headers,具有一定的參考價(jià)值,有興趣的同學(xué)可以了解一下2017-07-07angular inputNumber指令輸入框只能輸入數(shù)字的實(shí)現(xiàn)
這篇文章主要介紹了angular inputNumber指令輸入框只能輸入數(shù)字的實(shí)現(xiàn),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-12-12Angular?Component屬性綁定target和attr.target的區(qū)別分析
這篇文章主要介紹了Angular?Component屬性綁定target和attr.target的區(qū)別分析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-07-07Angularjs 根據(jù)一個(gè)select的值去設(shè)置另一個(gè)select的值方法
今天小編就為大家分享一篇Angularjs 根據(jù)一個(gè)select的值去設(shè)置另一個(gè)select的值方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-08-08AngularJS基礎(chǔ) ng-include 指令示例講解
本文主要介紹AngularJS ng-include 指令,這里對(duì)ng-include 指令的知識(shí)做了詳細(xì)整理介紹,有需要的朋友可以參考下2016-08-08解決angular的$http.post()提交數(shù)據(jù)時(shí)后臺(tái)接收不到參數(shù)值問(wèn)題的方法
這篇文章為大家分享了解決angular的$http.post()提交數(shù)據(jù)時(shí)后臺(tái)接收不到參數(shù)值問(wèn)題的方法,感興趣的小伙伴們可以參考一下2015-12-12