最近在angularjs項目當中,看到 controller
好多都是重複性的代碼,在 controller 當中有好多代碼很類似 function(好比 controller 下的 CRUD 方法),重複性工做太多。後來想,可不能夠提出一個service ,但仔細想一想,這些CRUD 原本就是從 Service 中調用的,若是在提出Service,會形成 Service 比較混亂,職責不清晰 。 由於本身作過一些後端,藉助後端的思想,是否是能夠 controller 繼承。html
// 參數的解釋 // constructor 能夠是 function 也能夠是 string // 若是傳入一個 function, 就會當成 controller 的構造函數 // 若是傳入一個 string,就會根據字符串去$controllerProvider 找 註冊的 controller //locals 是一個對象,注入來自局部的 controller ,在這裏咱們認爲 child controller $controller(constructor, locals, [bindings])
1.建立一個 base.controller.js
文件angularjs
(function() { 'use strict'; angular .module('DemoApp') .controller('BaseCtrl', BaseCtrl); //手動注入一些服務 BaseCtrl.$inject = ['$scope','CRUDServices']; /* @ngInject */ function BaseCtrl($scope,CRUDServices) { var _this = this; //當前 controller 提供一些方法 _this.bFormValid = formValid; activate(); //////////////// //初始化時候調用 function activate() { getList(); } // 獲取數據列表 function getList() { //把當前的結果賦值給 bList 屬性上 _this.bList = CRUDServices.getList(); } // 表單驗證 function formValid(){ //do some thing return false; } } })();
代碼很簡單,咱們在 BaseController
中提供了一個簡單的 formValid()
方法,還初始化調用了一個getList()
方法。後端
2.建立一個Service 。這個 service 來提供數據服務api
(function() { 'use strict'; angular .module('DemoApp') .service('ExtendServices', ExtendServices); ExtendServices.$inject = []; /* @ngInject */ function ExtendServices() { return { getList: getList //獲取 list 列表 } //////////////// function getList() { return [{ id: 1, name: '張三' }, { id: 2, name: '李四' }] } } })();
3.建立child.controller.js 文件
也就是咱們最主要的一個文件ide
(function() { 'use strict'; angular .module('DemoApp') .controller('ChildCtrl', ChildCtrl); //手動注入一些服務 //ExtendServices 用來提供數據的 Servie ChildCtrl.$inject = ['$scope', '$controller','ExtendServices']; /* @ngInject */ function ChildCtrl($scope, $controller,ExtendServices) { var vm = this; //調用咱們父 controller var parentCtrl = $controller('BaseCtrl', { $scope, $scope,CRUDServices:ExtendServices }) //經過 angular.extend 把父控制器上的 方法和屬性 綁定到 子的對象上 angular.extend(vm, parentCtrl); activate(); //////////////// function activate() { //調用表單驗證方法 vm.bFormValid(); } } })();
這樣,咱們經過 $controller service
實現了 controller 的繼承 ,也能夠把 child controller
須要的注入的服務 傳入到 base controller
當中 。({ $scope, $scope,CRUDServices:ExtendServices }
),咱們child controlller
一行代碼都沒有寫,就已經用了 獲取 列表的 magic power 。若是咱們須要調用表單驗證,直接調用 vm.bFormValid()
就能夠。函數
4.建立child.html 文件
,咱們直接 綁定就okthis
<div> <!-- 直接綁定 vm.bList 就會看到輸出結果--> <div ng-repeat="item in vm.bList">{{item}}</div> </div>
這樣下來之後咱們能夠提出一個 公共的 controller
,封裝一些經常使用的方法,在 controller
當中,只須要去寫關於業務不一樣的 方法。 代碼可維護性大大提升,代碼量也會減下來。spa