您的位置:首页 > Web前端 > AngularJS

初学angularJS笔记之Services服务

2015-09-13 00:00 495 查看
摘要: .value('uname','programDu') --定义变量
.constant('urls','http://www.websevc.com') --常亮
.factory()
.service() 两个方法相似,factory()复杂

HTML代码

<body ng-app="app" style="padding: 10px;">
<div ng-controller="CtrlSevers">
<h1>{{msg}}</h1>
<h3>{{uname}}</h3>
<a href="{{urls}}">ProgramDu</a>
<br />
<h3>{{data.msg}}</h3>
<h4>大家好,我是{{user.userName}},我的性别是{{user.userSex}}</h4>
<h5>{{ut}}</h5>
</div>
</body>


JavaScript代码

angular.module('app',[])
.value('uname','programDu')   //变量
.constant('urls','http://www.websevc.com')   //常量
.factory('Data',function(){
return {
msg:'你好',
setMsg:function(){
this.msg = 'ProgramDu';
}
}
})

.service('User',function(){
this.userName = 'ProgramDu';
this.userSex = '男';
this.setUser = function(){
return '大家好,我是'+this.userName+',我的性别是'+this.userSex;
}
})

.controller('CtrlSevers',function($scope,uname,urls,Data,User){
$scope.msg = 'ss';
$scope.uname = uname;
$scope.urls = urls;

$scope.data = Data;
Data.setMsg();

$scope.user = User;
$scope.ut = User.setUser();

})


factory 方法解释,在方法里面多套了一层 return

.factory('Data',function(){
return new fun();
})

function fun(){
this.userName = 'ProgramDu';
this.userSex = '男';
this.setUser = function(){
return '大家好,我是'+this.userName+',我的性别是'+this.userSex;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息