博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
angularjs 中使用 service 在controller 之间 share 对象和数据
阅读量:4683 次
发布时间:2019-06-09

本文共 2003 字,大约阅读时间需要 6 分钟。

文章来自:http://www.cnblogs.com/slardar1978/p/4203822.html

在做angularjs 的UI 时,我们经常会遇到一个页面之间有几个controller,在controller 之间share 公共的一些数据和方法就变得比较困难,目前推荐的做法是创建一个service, 在service 中存储公共的数据,然后把service 注入到controller中来达到share 数据的目的。

下面是最简单的一个sample 列子

angularjs 模板页面, 有userContoller 和 customerController,我们将在这两个controller 之间共享数据, 具体定义如下:

angularjs sample

{
{golbal_sitename}}
{
{controllerName}}

{
{golbal_sitename}}
{
{controllerName}}

 

angularjs js 页面, 在这个代码中我们定义了 module APP, userController 和customerController, 另外我们还定义了一个service, dataService,这个service 包含需要共享的数据和方法,在这里我们返回了一个属性golbal_sitename, 和 一个sayHello 方法。

然后,在声明controller 的时候,我们把dataservice 这个对象分别注入到userController 和customerController,注入完成后,我们就可以在controller 的代码中访问dataService共享的数据了。

var APP = angular.module('APP',[]).controller('userController', ['$scope','dataService',function($scope,dataService) {       $scope.controllerName='userController';       $scope.golbal_sitename=dataService.golbal_sitename;       $scope.sayHello =function(){           dataService.sayHello($scope.controllerName);       }}]).controller('customerController',['$scope','dataService', function($scope,dataService) {       $scope.controllerName='customerController';       $scope.golbal_sitename=dataService.golbal_sitename;       $scope.sayHello =function(){           dataService.sayHello($scope.controllerName);       }}]).factory('dataService',function(){    return {        golbal_sitename:"this is the shared value",        sayHello:function(msg){            alert(msg);        }    }});

最后的结果截图如下:

 

从图中我们可以看到

”this is the shared value“ 值来自dataService
sayHello 的具体实现也是在dataService中定义的。
 
这样我们就实现了在controller 之间共享对象。
 
完整demo : 

转载于:https://www.cnblogs.com/Uncle-Maize/p/6291951.html

你可能感兴趣的文章
用CSS开启硬件加速来提高网站性能(转)
查看>>
使用BufferedReader的时候出现的问题
查看>>
加快页面加载速度的方法
查看>>
Oozie协作框架
查看>>
linux安装图形界面
查看>>
Android广播发送失败
查看>>
博弈论之入门小结
查看>>
使用checked关键字处理“溢出”错误
查看>>
L1-Day57
查看>>
angular路由配置用法
查看>>
effective c++ 条款19:设计class犹如设计type
查看>>
Todolist总结
查看>>
解决IE8下opacity属性失效问题,无法隐藏元素
查看>>
洛谷1002 过河卒
查看>>
C#匿名函数的坑
查看>>
标记页面控件尺寸
查看>>
批处理文件中的路径问题
查看>>
appium+python 环境搭建
查看>>
WampServer下修改和重置MySQL密码
查看>>
hibernate出现No row with the given identifier exists问题
查看>>