扩展控制器组件angularjs

extend controller component - angularjs

本文关键字:angularjs 组件 控制器 扩展      更新时间:2023-09-26

我使用angular 1.5来开发我的应用程序,我使用.component()。我有三个组件和它们的控制器,它们都很相似。如何将控制器从comp1扩展到comp2 ?

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

comp1.js comp2.js comp3.js

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

父组件(从):

/**
 * 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;
  };
});

子组件(扩展的那个):

/**
 * 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;
  };
});

你可以在子控制器中定义新方法,覆盖现有方法,调用父方法,等等。

我建议您简单地使用服务来共享和组合组件。然后,您可以跳过担心.extend(), $controller等的复杂性。

  angular
    .module('app')
    .factory('component.utils', function() {
       return {
         sharedProp: 'foo',
         sharedMethod: function() { return 'bar' }
       }
    })
    // components can all easily use functionality 
    // provided by one (or more) services, w/o 
    // needing a complicated inheritance model.
    .component('foo', {
      templateUrl: 'foo.html',
      controller: [
        'component.utils',
        function(utils) {
          this.$onInit = function() {
            this.prop = utils.sharedProp;
            utils.sharedMethod();
            // now do other foo things...
          }
        }
      ]
    })
    .component('bar', {
      templateUrl: 'foo.html',
      controller: [
        'component.utils',
        function(utils) {
          this.$onInit = function() {
            this.prop = utils.sharedProp;
            utils.sharedMethod();
            // now do other bar things...
          }
        }
      ]
    });

继承有它的位置,但倾向于组合而不是继承通常是更好的解决方案。篇文章。