how angular controller (and scope) inheritance works

前端 未结 3 1707
梦谈多话
梦谈多话 2020-12-12 03:49

I\'m trying to figure out how controller inheritance works. I have three controllers:

var myApp = angular.module(\'app\', []);

myApp.controller(\'MainContro         


        
3条回答
  •  孤城傲影
    2020-12-12 04:15

    Here's an example of how controllers can be extended in Angular.

    myApp.service('baseCtrl', function () {
      this.name = 'base';
      this.getName = function() {
        return this.name;
      };
    });
    
    myApp.controller('MainController', ['baseCtrl', function (baseCtrl) {
      angular.extend(this, baseCtrl);
      this.name = 'main';
    }]);
    myApp.controller('Child1', ['baseCtrl', function (baseCtrl) {
      angular.extend(this, baseCtrl);
      this.name = 'child1';
    }]);
    myApp.controller('Child2', ['baseCtrl', function (baseCtrl) {
      angular.extend(this, baseCtrl);
      this.name = 'child2';
    }]);
    

    It obliges to use controllerAs, which replaces $scope with this, it is especially good for such cases.

    Notice the usage of service instead of other Angular service types, it uses new under the hood, so this... statements can be brought right from a controller to separate service.

    There are several ways of doing controller inheritance. Here is another approach.

    Regarding the original code, there is no 'controller iheritance' in Angular. And $scope prototypical inheritance assumes that

    $scope.getName = function() {
        return $scope.name;
    };
    

    returns $scope.name from the context where it was defined, it is MainController function in your case.

提交回复
热议问题