扩展控制器组件 - angularjs

Ami*_*ine 5 javascript components angularjs

我使用 angular 1.5 来开发我的应用程序,我正在使用.component(). 我有三个组件及其控制器,所有这些都非常相似。如何扩展控制器comp1以使用它comp2

每个组件在一个单独的 js 文件中:

comp1.js comp2.js comp3.js

Ada*_*eis 1

您也可以相互扩展组件控制器。使用以下方法:

父组件(从中扩展):

/**
 * Module definition and dependencies
 */
angular.module('App.Parent', [])

/**
 * Component
 */
.component('parent', {
  templateUrl: 'parent.html',
  controller: 'ParentCtrl',
})

/**
 * Controller
 */
.controller('ParentCtrl', function($parentDep) {

  //Get controller
  const $ctrl = this;

  /**
   * On init
   */
  this.$onInit = function() {

    //Do stuff
    this.something = true;
  };
});
Run Code Online (Sandbox Code Playgroud)

子组件(扩展的一个):

/**
 * Module definition and dependencies
 */
angular.module('App.Child', [])

/**
 * Component
 */
.component('child', {
  templateUrl: 'child.html',
  controller: 'ChildCtrl',
})

/**
 * Controller
 */
.controller('ChildCtrl', function($controller, $parentDep) {

  //Get controllers
  const $ctrl = this;
  const $base = $controller('ParentCtrl', {$parentDep});

  //Extend
  angular.extend($ctrl, $base);

  /**
   * On init
   */
  this.$onInit = function() {

    //Call parent init
    $base.$onInit.call(this);

    //Do other stuff
    this.somethingElse = true;
  };
});
Run Code Online (Sandbox Code Playgroud)

您可以在子控制器中定义新方法、覆盖现有方法、调用父方法等。效果非常好。