angular service讲解

controller是相对独立的,也就是说,两个controller之间,内存是不共享的,这个controller是无法访问其他其他controller的属性或者方法的;

 

以前,我都是通过localStorage来进行储存,后来发来localStorage应该是用来存储持久化数据,用来存储临时数据,controller互相交互,官方建议通过service来进行相互访问。
 
也就是说, service是用于不同controller或者directive中用于共享数据的一种服务。
 
举例说明:
html
<!-- 一个controller -->
    <div style="background: yellow;" ng-controller="worldCtrl">
        {{author.name}}
        <br/> {{author.sex}}
        <button ng-click="update()">同步数据</button>
    </div>

    <!-- 另一个controller -->
    <div ng-controller="helloCtrl">
        {{author.name}}
        <br/> {{author.sex}}
        <button ng-click="updatePublic()">更新公有变量</button>
    </div>

controller.js

var app = angular.module('Hello', []);

app.controller('worldCtrl', function($scope, demoService) {
    $scope.author = demoService.publicAuthor;
    
    $scope.update = function() { //同步数据
        $scope.author = demoService.publicAuthor;
    }
});

app.controller('helloCtrl', function($scope, demoService) {
    $scope.author = demoService.publicAuthor;

    $scope.updatePublic = function() { //更新您数据
        demoService.publicAuthor = {
            name: 'fei',
            sex: 'female'
        }
        $scope.author = demoService.publicAuthor;
    }
});

service.js

app.service('demoService', function () {
    var privateAuthor = {              //私有变量
        name: 'jack',
        sex: 'male'
    }

    this.publicAuthor = {        //共有变量
        name: 'rose',
        sex: 'female'
    }

    this.getPriAuthor = function () {          //获取私有变量
        return publicAuthor;
    }
});

end.

posted on 2016-04-21 19:04  发哥要做活神仙(笔记) 阅读( ...) 评论( ...) 编辑 收藏

转载于:https://www.cnblogs.com/91allan/p/5418308.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值