前端框架——AngularJS学习之服务层service

上篇文章中,学习了入门angularJS,并实现了一些小Demo。但是在代码中,js和html都放在一起,并不利于我们后期的维护。我们可以在前端代码中也运用MVC的设计模式,并将代码进行分离,提高程序的可维护性。

1.自定义服务

在angularJS中,服务是一个函数或对象,可在你的AngularJS应用中使用。上篇文章使用了内置服务$http,其实可以自己来定义服务,而服务会封装一些操作。在不同的控制器中可以调用同一个服务,这样服务的代码将会被重用。

例如:

不使用服务层:

var app=angular.module('pinyougou', []);//定义模块    
        app.controller('brandController' ,function($scope,$http){            
            //读取列表数据绑定到表单中  
            $scope.findAll=function(){
                $http.get('../brand/findAll.do').success(
                    function(response){
                        $scope.list=response;
                    }            
                );
            }
        });

假设,有不止一个方法都需要请求../brand/findAll.do,那么都需要写一篇这个请求。如果现在这个请求地址改变了,那就需要每个方法都要改变,代码的复用性不高。

使用服务层

var app = angular.module('pinyougou',['pagination']);
        //品牌服务
        app.service('brandService', function($http) {
            this.findAll = function() {
                return $http.get('../brand/findAll.do');
            }

        });
        
        app.controller('brandController',function($scope, brandService){
            //查询品牌列表
            $scope.findAll = function() {
                brandService.findAll().success(
                    function(response) {
                        $scope.list = response;
                    }        
                );
            }
        });

 

posted @ 2019-02-21 16:52  MichaelKai  阅读(202)  评论(0)    收藏  举报