码迷,mamicode.com
首页 > 其他好文 > 详细

angular service讲解

时间:2016-04-21 20:35:22      阅读:112      评论:0      收藏:0      [点我收藏+]

标签:

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.

angular service讲解

标签:

原文地址:http://www.cnblogs.com/91allan/p/5418308.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!