继承角度控制器对象

时间:2014-11-12 20:43:32

标签: angularjs inheritance

当我们在IIFE中包围控制器对象时,我真的不明白如何以角度(不使用$ scope)继承控制器对象。

假设我们有2个控制器文件:

Animal.js

(function() {
    'use strict';
    angular.module('myApp').controller('animalCtrl', function() {
        this.strength = 3;
        this.speed = 3;
});
})();

Beaver.js

(function() {
    'use strict';
    angular.module('myApp').controller('beaverCtrl', function() {
        //How do I inherit the parent controllers stats?
});
})();

如何使用myaverCtrl继承animalCtrl?

2 个答案:

答案 0 :(得分:2)

在任何angularjs站点上共享数据的最佳方式是使用服务。在这种情况下,我会创建一个存储强度和速度的工厂,并与beaverCtrl共享它。

angular.module('<yourappname>', [])
  .factory('dataService', function() {
    $scope = this;

    $scope.strength = null;
    $scope.speed = null;

    $scope.setStrength = function(value) {
      $scope.strength = value;
    }

    $scope.setSpeed = function(value) {
      $scope.speed = value;
    }
    return $scope;
})

然后在控制器中你可以像这样调用服务

.controller('animalCtrl', function(dataService) {
  this.strength = 3;
  this.speed = 3;

  dataService.setStrength(this.strength);
  dataService.setSpeed(this.speed);

});

.controller('beaverCtrl', function(dataService) {
  this.strength = dataService.strength;
  this.speed = dataService.speed;
});

答案 1 :(得分:2)

重要的是要意识到AngularJS控制器只是一个普通的javascript“类”。唯一的问题是使用依赖注入调用基础构造函数。

// Create some base class.
BaseController = function($scope, $route) {
  // Do some stuff here.
};

// The base class has some behavior.
BaseController.prototype.someMethod = function() { /* do something */ };

// Create some child class.
ChildController = function($scope, $injector) {
  // Invoke the base constructor.
  $injector.invoke(this, BaseController, {$scope: $scope});
};

// Inherit from the base class.
ChildController.prototype = Object.create(BaseController.prototype);

// Add more specific behavior.
ChildController.prototype.someChildMethod = function() { /* do something */ };

然后您可以将控制器注册为

angular.module('myApp').controller('ChildController', ChildController);

请记住,如果过度使用,使用这样的继承会有问题。它只应用于共享行为。另外,使用不同“类”的组合通常比使用继承更灵活。

从代码组织的角度来看,我还建议您在一个地方声明您的控制器(每个控制器一个文件)并将它们注册到另一个地方的模块(每个模块一个文件)。

相关问题