角度扩展控制器方法

时间:2016-06-04 18:38:18

标签: javascript angularjs

在angularJs中,我有一堆控制器,它们有一些相同的功能:

angular.module('myApp').controller(...){

    function lockForm(id){
        ...
    }

    function releaseForm(id){
        ...
    }

    function dbError(e){
        ...
    }

    // and some other little stuff again and again in every controller
}

我读过的例子都是基于$ scope和@this的扩展(mixin)内容。有没有办法按原样扩展整个控制器?

感谢Shushanth Pallegar我解决了我的问题。它不是我想要的,但比以前更好。

// base ctrl
angular.module('myApp').controller('baseViewCtrl', function ($scope, viewData) {

        this.lockForm = function() {
            viewData.isLoading = true;
        };

        // ... and others

});


// child ctrl
angular.module('myApp').controller('childCtrl', function ($scope) {
        var viewData = {
            // some stuff
        };

        // inject from basecontroller
        angular.extend(this, $controller('baseViewCtrl', {$scope: $scope, viewData: viewData}));

        // link $scope
        $scope.viewData = viewData;
        $scope.onSelectUnit = onSelectUnit;

        // child controller methods
        function onSelectUnit(){
            this.lockForm();
            ...
        }
});

它看起来有点难看,因为我几乎到处都避免了@this

也许我这样做并使用base而不是@this来更清楚地表明有注入的方法:

// child ctrl
angular.module('myApp').controller('childCtrl', function ($scope) {
        var viewData = {
            // some stuff
        };

        // inject from basecontroller
        var base = $controller('baseViewCtrl', {$scope: $scope, viewData: viewData});

    // link $scope
    $scope.viewData = viewData;
    $scope.onSelectUnit = onSelectUnit;

    // child controller methods
    function onSelectUnit(){
        base.lockForm();
        ...
    }

1 个答案:

答案 0 :(得分:3)

使用$ controller服务并传递您需要扩展的控制器名称,如下所示

家长控制器

  angular.module('myApp').controller('parentController',function(){

     $scope.lockForm = function(id){
        ...
    }
  });

子控制器

angular.module('app').controller('childController',function($controller){

    var parentController = $controller('parentController',{$scope:$scope});

     console.log(parentController.lockForm);

  });

参考$controller

按顺序延伸至this,使用如下

angular.module('app').controller('childController',function($controller){

    var parentController = $controller('parentController',{$scope:$scope});
     angular.extend(this,parentController);

     console.log(this.lockForm);

  });

如果您使用的函数将这些函数附加到作用域,则需要按以下方式返回这些函数。

 angular.module('myApp').controller('parentController',function(){

         var _lockForm = function(id){
            ...
        }

       return{
          lockForm = _lockForm
       }

      });

所以你的扩展控制器可以使用如下

 var extendedController = $controller('parentController',{$scope:$scope});

    extendeController.lockForm('123');