在 AngularJs 中共享数据 [英] Share Data in AngularJs

查看:26
本文介绍了在 AngularJs 中共享数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将数据分享给所有控制者?

How to Share data to all controller?

我有一个控制器从服务器(file.json)中提取数据,我想与其他控制器共享

I have a controller that pull data from server(file.json) that i want to share to other controller

sampleApp.controller('PhoneListCtrl', 
['$scope', '$http', 
function($scope, $http) {
    $http.get('App_Data/phonelist.json').
        success(function(returnDataFrmJson){
            $scope.phonesScope = returnDataFrmJson;
        });
}]);

将访问第一个共享数据的控制器

controller that will access the shared data of the first one

sampleApp.controller('AddIPhoneController', 
['$scope', '$http',
function($scope, $http) { 
    $scope.newInput= 'sample text';

    $scope.sharedText= dataFromSharedControll;
}]);

将显示数据的 html 文件.

the html file that will show the data.

{{newInput}} {{sharedText}}

推荐答案

好吧,有多种选项供您使用:$sessionStoragelocalStorageappConstant$localStorage 等等.

Well, there are various options for you like using: $sessionStorage, localStorage, appConstant, $localStorage and so on.

您甚至可以使用FactoryServices 在控制器之间共享数据.我会给你一个使用 $sessionStorage 的简单例子.

You can even share the data between controllers using Factory and Services. I will be giving you a simple example of using $sessionStorage.

为了使用$sessionStorage$localStorage,你需要注入ngStorage.

In order to use $sessionStorage or $localStorage, you need to inject ngStorage.

首先在你的 index.html 中,包含源代码:

First in your index.html, include the source:

<script src="https://rawgithub.com/gsklee/ngStorage/master/ngStorage.js"></script>    

然后在您的模块定义中,注入 ngStorage:

Then in your module definition, inject the ngStorage:

var sampleApp = angular.module('Your App Name', ['ngStorage']);  

并且,在您的 controllers 中:

sampleApp.controller('PhoneListCtrl', 
['$scope', '$http', '$sessionStorage',
function($scope, $http,$sessionStorage) {
    $http.get('App_Data/phonelist.json').
        success(function(returnDataFrmJson){
            $scope.phonesScope = returnDataFrmJson;
            $sessionStorage.sharedValue = returnDataFrmJson;//keeping the value in session
        });
}]);    

controller 将访问第一个的共享数据

controller that will access the shared data of the first one

sampleApp.controller('AddIPhoneController', 
['$scope', '$http','$sessionStorage',
function($scope, $http,$sessionStorage) { 
    $scope.newInput= 'sample text';

    $scope.sharedText= $sessionStorage.sharedValue;
}]);

然后在您的 View 中:

{{newInput}}{{sharedText}}

这篇关于在 AngularJs 中共享数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆