AngularJs 自定义service服务

service服务
	相当于本身已经构建了一个空白对象,通过this.来操作,不是通过this.创建的内容,需
	要提供一个this.方法来对外暴露返回/修改,否则无法取值

	语法:app页面数据模型.service('自定义service服务名字',function()
	{
		通过this.添加内容;
		...
	})

代码示例:

<html ng-app='app' ng-controller='main' >
<head>
	<meta charset="utf-8">
	<meta name='viewport' content='width=device-width,user-scalable=no,initial-scale=1.0,maximum-scale=1.0,minimum-scale=1.0'>
	<title ng-bind='mainTitle'></title>

	<script src='js/angular.js'></script>
	<script src='js/angular.route.min.js'></script>	
	<style>

	</style>
</head>
<body >
<!-- 向全局变量存储内容 -->
<div class='div1' ng-controller='con'>
	<input type="text" ng-model='msg'>
	<button ng-click='submit(msg)'>保存</button>	
</div>

<!-- 向全局变量获取内容 -->
<div class='div2' ng-controller='con2'>
<p ng-bind='showMsg'></p>
<button ng-click='download()'>下载</button>
		
</div>
 

<script>
	var app=new angular.module('app',[]);

	app.service('ssr',function(){
		this.pname='jeff'
		var sec='密码';
		this.getSec=function()
		{
			return sec;
		}
		this.setSec=function(temp)
		{
			sec=temp;
		}
	});


	app.controller('main',['$scope',function($scope){
		$scope.mainTitle='value';
	}])

	app.controller('con',['$scope',function($scope){
		$scope.msg='';
		$scope.submit=function(temp)
		{
			//向全局变量存入msg
			
		}

	}])

	app.controller('con2',['$scope','ssr',function($scope,ssr){
			$scope.showMsg='';

			$scope.download=function()
			{
				console.log(ssr.pname);
				console.log(ssr.getSec());
				ssr.setSec('密码2');
				console.log(ssr.getSec());


			}

	}])
</script>
</body>
</html>

发布了300 篇原创文章 · 获赞 3 · 访问量 6388

猜你喜欢

转载自blog.csdn.net/weixin_43294560/article/details/104052405
今日推荐