让AngularJS的controllers之间共享数据

 

如何让controller之间共享数据呢?大致是让不同controller中的变量指向同一个实例。

通过service创建一个存放共享数据的对象。

 

.service("greeting", function Greeting(){
    var greeting = this;

    greeting.message = "default";
})

 

让不同的controller中的变量指向Greeting这个实例。

 

.controller('FirstCtrl', function FirstCtrl(greeting){
    var first = this;
    first.greeting = greeting;
})
.controller('SecondCtrl', function SecondCtrl(greeting){
    var second = this;
    second.greeting = greeting;
})

 

以上,FirstCtrl和SecondCtrl中的greeting变量都指向Greeting这个实例。这样FirstCtrl和SecondCtrl共享同一个Greeting实例。


具体实现,先看文件结构:
templates/
.....first.html
.....second.html
app.js
index.html

index.html

 

<!DOCTYPE html>
<html lang="en" ng-app="app">
<head>
  <meta charset="UTF-8">
  <title></title>
  <link rel="stylesheet" href="../../node_modules/bootstrap/dist/css/bootstrap.min.css"/>
  <style>
    body{
      padding:20px;
    }
  </style>
</head>
<body>

<div class="container">
  <ui-view></ui-view>
</div>


<script src="../../node_modules/angular/angular.min.js"></script>
<script src="../../node_modules/angular-ui-router/build/angular-ui-router.min.js"></script>
<script src="app.js"></script>
</body>
</html>

 

以上,ui-view是用来呈现不同的视图。

app.js

 

angular.module('app',['ui.router'])
    .config(function config($stateProvider){
        $stateProvider.state('index',{
            url:"",
            controller: "FirstCtrl",
            controllerAs: "first",
            templateUrl:"templates/first.html"
        });

        $stateProvider.state('second',{
            url:"/second",
            controller:"SecondCtrl as second",
            templateUrl: "templates/second.html"
        });
    })
    .service("greeting", function Greeting(){
        var greeting = this;

        greeting.message = "default";
    })
    .controller('FirstCtrl', function FirstCtrl(greeting){
        var first = this;
        first.greeting = greeting;
    })
    .controller('SecondCtrl', function SecondCtrl(greeting){
        var second = this;
        second.greeting = greeting;
    })

 

以上,在angular-ui-router.min.js中封装了ui.router这个module,需要依赖它。

first.html

 

<input type="text" ng-model="first.greeting.message"/>

<div ng-class="first.greeting.message">
  {{first.greeting.message}} {{'world'}}
</div>

<div ui-sref="second">Go to second</div>

 

以上,文本框通过ng-model和first.greeting.message进行了双向绑定,即同Greeting这个实例的message进行了双向绑定。

second.html

<h1>{{second.greeting.message}}</h1>

当更改first.html中文本框的值,这里的值也会相应变化。

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值