AngularJS:共享在两个不同的页面的不嵌套份同一控制器的数据 [英] AngularJS: share the data of the same controller in two different, not nested parts of the page

查看:251
本文介绍了AngularJS:共享在两个不同的页面的不嵌套份同一控制器的数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在我的网页两地间共用一个控制器的数据。例如:

I want to share the data of one controller between two places in my page. For example:

<div ng-app="myApp">
    <div ng-controller="myController">
        <input type="text" ng-model="x" /> {{x}}
    </div>
</div>
<!-- these are in totally different places and I do not want, nor can't nest them -->
<div ng-app="myApp">
    <div ng-controller="myController">
        <input type="text" ng-model="x" /> {{x}}
    </div>
</div>

当然,这样的:

var myApp = angular.module('myApp', []);
myApp.controller('myController', function($scope) {
    $scope.x = 'test';
});

我能做些什么,这样,无论是什么类型我第一次输入文本将反映在第二?反之亦然?基本上是相同的数据被传播到这两部分,同时维持该数据的一个副本。

What can I do so that, no matter what I type first input text will be reflected in the second? And vice versa? Basically the same data being propagated to these two sections, while maintaining a single copy of the data.

在这里的jsfiddle: http://jsfiddle.net/LETAd/

JSFiddle here: http://jsfiddle.net/LETAd/

PS:我手动引导它,如果这是任何意义的。

PS: I bootstrap it manually, if this is of any relevance.

谢谢!

推荐答案

要共享控制器之间的数据,通常一个服务是您最佳的选择。将共享数据到服务,并注入该服务到控制器:

To share data between controllers, normally a service is your best option. Put the shared data into the service, and inject the service into the controller:

function myController($scope, MyService) {

每个范围/控制器实例随后将能够访问共享数据。

Each scope/controller instance will then be able to access the shared data.

注意,服务是单身,所以只会有你周围的共享数据的一个实例。

Note that services are singletons, so there will only be one instance of your shared data around.

下面是一个小提琴(我没有写),显示两个控制器如何共享数据。

Here is a fiddle (I didn't write it) showing how two controllers can share data.

另请参阅并搜索<一间href=\"http://stackoverflow.com/questions/12008908/pass-variables-between-controllers\">传递变量href=\"http://stackoverflow.com/questions/13840489/angularjs-two-way-data-bindings-and-controller-reload\">Angularjs:双向数据绑定和控制器重装。

这篇关于AngularJS:共享在两个不同的页面的不嵌套份同一控制器的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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