首页 > 解决方案 > 扩展控制器在提交时具有未定义的形式

问题描述

好的,我有一个主控制器和另一个我扩展主控制器(以显示不同的布局)的控制器。

主控制器:

function CustomerInformationController(...) {
    var vm = this;
    ...

    vm.save = function() {
        if (angular.isDefined(vm.guestAccountForm)) {
            ...
        }
        ...

主模板:

<div ng-controller="CustomerInformationController as customerInformation" class="customer-information">
    <form name="customerInformation.guestAccountForm">
    ...
    </form>
</div>

扩展控制器:

function CustomerInformationControllerExtent($controller, $scope) {
    var vm = this;

    // Extend Product Controller.
    angular.extend(this, $controller('CustomerInformationController', { $scope: $scope }));

扩展模板(我希望能够重新设计这个模板并覆盖它):

<div ng-controller="CustomerInformationControllerExtent as customerInformation" class="customer-information">
    <form name="customerInformation.guestAccountForm">
    ...
    </form>
</div>

当我只使用主控件时,一切都很好,但是在控制器扩展中,当我尝试检查表单是否有效时,vm.guestAccountForm是未定义的。

但是,当我尝试使用this( this.guestAccountForm) 时,没关系。

我错过了扩展功能的东西吗?

标签: javascriptangularjscontroller

解决方案


一种方法是将vm对象作为本地注入:

function CustomerInformationControllerExtent($controller, $scope) {
    var vm = this;

    // Extend Product Controller.
    angular.extend(this, $controller('CustomerInformationController', { vm  vm}));

然后使用注入的vm对象:

function CustomerInformationController(vm) {
    ̶v̶a̶r̶ ̶v̶m̶ ̶=̶ ̶t̶h̶i̶s̶;̶
    ...

    vm.save = function() {
        if (angular.isDefined(vm.guestAccountForm)) {
            ...
        }
        ...

this对象与控制器的对象xController不同。这就是为什么使用。它将属性从一个对象复制到另一个对象。thisxControllerExtentangular.extendthis

坦率地说,我不认为这是最明智的做法。如果您想在控制器之间共享通用功能,请将这些通用功能放在服务中。


推荐阅读