让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中文本框的值,这里的值也会相应变化。

原文地址:https://www.cnblogs.com/darrenji/p/5082738.html