AngularJs之自定义服务实现多个控制器之间的数据共享,在同一页面当中,多处用到同一个数据,一般情况下我们需要重复写很多次代码,但是使用Angular提供的自定义服务,可以只写一次代码,提供给很多模块和控制器使用,这样可以减少代码沉兑。具体代码如下:
html部分:
02 | <div ng-controller= "ctr1" > |
03 | <table cellpadding= "0" cellspacing= "0" > |
11 | < tr ng-repeat= "(key, value) in data" > |
12 | <td>{{value.webname}}</td> |
13 | <td>{{value.weburl}}</td> |
19 | <div ng-controller= "ctr2" > |
20 | <table cellpadding= "0" cellspacing= "0" > |
28 | < tr ng-repeat= "(key, value) in data" > |
29 | <td>{{value.webname}}</td> |
30 | <td>{{value.weburl}}</td> |
|
JavaScript部分:
01 | var m = angular.module( 'app' , []); |
02 | m.factory( 'zymBlog' , [ '$http' , function ($http){ |
08 | }).then( function (result){ |
14 | m.controller( 'ctr1' , [ '$scope' , 'zymBlog' , function ($scope, zymBlog){ |
15 | zymBlog.get().then( function (result){ |
19 | m.controller( 'ctr2' , [ '$scope' , 'zymBlog' , function ($scope, zymBlog){ |
20 | zymBlog.get().then( function (result){ |
|
以上,使用factory自定义服务,第一个参数是服务名称,第二个参数是数组,包含需要依赖注入的其他服务,通过这个自定义服务获取到数据,其他的控制器都可以进行使用!