angular service讲解
2016-04-21 19:04
731 查看
controller是相对独立的,也就是说,两个controller之间,内存是不共享的,这个controller是无法访问其他其他controller的属性或者方法的;
以前,我都是通过localStorage来进行储存,后来发来localStorage应该是用来存储持久化数据,用来存储临时数据,controller互相交互,官方建议通过service来进行相互访问。
也就是说,service是用于不同controller或者directive中用于共享数据的一种服务。
举例说明:
html
controller.js
service.js
end.
以前,我都是通过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学习(三)—— Controller
- AngularJS的学习
- 在AngularJS中使用jQuery的zTree插件的方法
- 谈谈AngularJS中的一次性数据绑定
- AngularJS中实现用户访问的身份认证和表单验证功能
- Angularjs基础(六)
- 使用Yeoman搭建 AngularJS 应用 (12) —— 让我们搭建一个网页应用
- AngularJs ui-router 路由的简单介绍
- 使用Yeoman搭建 AngularJS 应用 (11) —— 让我们搭建一个网页应用
- 第一个AngularJS Web应用 todoList
- angularJS 二
- 使用Yeoman搭建 AngularJS 应用 (10) —— 让我们搭建一个网页应用
- AngularJs 第一个自定义指令编写
- 使用Yeoman搭建 AngularJS 应用 (9) —— 让我们搭建一个网页应用
- angular filter ng-repeat 用法
- 使用Yeoman搭建 AngularJS 应用 (8) —— 让我们搭建一个网页应用
- AngularJS的学习--$on、$emit和$broadcast的使用
- ionic入门之AngularJS扩展
- AngularJS学习笔记之基本指令(init、repeat)
- 使用Yeoman搭建 AngularJS 应用 (7) —— 让我们搭建一个网页应用