微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

angularjs-factory,provider,service,constant,value,decorator

1、factory

Factory 就是创建一个对象,为它添加属性,然后把这个对象返回出来。你把 service 传进 controller 之后,在 controller 里这个对象里的属性就可以通过 factory 使用了。

<!doctypehtml>
<htmllang="en">
<head>
<Metacharset="UTF-8">
<title>Document</title>
<scriptsrc="angular.min.js"></script>
<script>
angular.module('mod',[])
//定义工厂模块-factory
.factory('fact',[function(){
return{
str:"testfactory",sum:function(n1,n2){
returnn1+n2
}
};
}])
//添加依赖注入模块fact
.controller('testCtrl',['$scope','fact',function($scope,fact){
alert(fact.str)
}])
</script>
</head>
<bodyng-app='mod'ng-controller='testCtrl'>

</body>
</html>

2、provide

Providers是唯一一种你可以传进 .config() 函数的 service。当你想要在 service 对象启用之前,先进行模块范围的配置,那就应该用 provider。

<!doctypehtml>
<htmllang="en">
<head>
<Metacharset="UTF-8">
<title>Document</title>
<scriptsrc="angular.min.js"></script>
<script>
angular.module('mod',[])
.controller('modCtrl','prod',prod){
alert(prod.a+prod.b)
}])
.provider('prod',[function(){
this.$get=[function(){
return{
a:12,b:15
};
}];
}])
</script>
</head>
<bodyng-app='mod'ng-controller='modCtrl'>

</body>
</html>

3、service

Service是用"new"关键字实例化的。因此,你应该给"this"添加属性,然后 service 返回"this"。你把 service 传进 controller 之后,在controller里 "this" 上的属性就可以通过 service 来使用了。

<!doctypehtml>
<htmllang="en">
<head>
<Metacharset="UTF-8">
<title>Document</title>
<scriptsrc="angular.min.js"></script>
<script>
angular.module('mod',[])
.service('serv',[function(){
this.a=12
}])
.controller('modCtrl','serv',serv){
alert(serv.a)
}])
</script>
</head>
<bodyng-app='mod'ng-controller='modCtrl'>

</body>
</html>

4、constant与value

constant不可修饰

<!doctypehtml>
<htmllang="en">
<head>
<Metacharset="UTF-8">
<title>Document</title>
<scriptsrc="angular.min.js"></script>
<script>
angular.module('mod',[])
.constant('VERSION','5.0.3')
.value('name','cisco')
.controller('modCtrl','VERSION','name',VERSION,name){
alert(name+':'+VERSION)
}])
</script>
</head>
<bodyng-app='mod'ng-controller='modCtrl'>

</body>
</html>

5、decorator

<!doctypehtml>
<htmllang="en">
<head>
<Metacharset="UTF-8">
<title>Document</title>
<scriptsrc="angular.min.js"></script>
<script>
angular.module('mod',name,prod){
alert(name+''+prod.nxos+''+prod.type+''+prod.date+''+VERSION)
}])
.provider('prod',[function(){
this.$get=[function(){
return{
nxos:'nxos',type:'5548'
};
}];
}])
.decorator('prod',function($delegate){
$delegate.date='2007.1.10'
return$delegate
})
</script>
</head>
<bodyng-app='mod'ng-controller='modCtrl'>

</body>
</html>

原文地址:https://www.jb51.cc/angularjs/146945.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐