4

当嵌套在 ng-scope 中时,我遇到了 ng-form 没有在范围内设置表单的问题。

例如

<div ng-controller='TestCtrl'>
    <ng-switch on="switchMe">
        <div ng-switch-default>Loading...</div>
        <div ng-switch-when="true">
            <form name="nixTest">
                <input placeholder='In switch' ng-model='dummy'></input>
                <button ng-click="test()">Submit</button>
            </form>
        </div>
    </ng-switch>
</div>

控制器:

controllers.TestCtrl = function ($scope) {
    $scope.switchMe = true;
    $scope.test = function () {

        if ($scope.nixTest) {
            alert('nixTest exists')
        } else {
            alert('nixTest DNE')
        }
    }
}

有什么解决方法吗?测试小提琴可以在这里找到

4

2 回答 2

3

ng-switch 创建一个子作用域,并在此作用域上创建表单。因此,子范围表单在父范围上不可用。

要访问它,您可以将其传递test()ng-click=test(nixTest). 因此范围方法签名也需要更新以支持输入参数。

于 2013-08-26T16:25:59.910 回答
0

我遇到了同样的问题。不幸的是,我无法轻松应用Chandermani的解决方案,因为我需要在父范围$on内通过调用访问表单名称。ng-switch因此,我求助于创建一个指令,将表单的名称发送到$rootScope

.directive("globalName", ["$rootScope", function($rootScope) {
    return function(scope, element) {
        $rootScope["get_" + element.attr('name')] = function() {
            return scope[element.attr('name')];
        };
    }
}]);

用法是这样的:

<form name="whatever" novalidate global-name>...</form>

然后您访问控制器中的表单,例如:

$scope.get_whatever().$setPristine();
$scope.get_whatever().$setUntouched();

作为 中的名称$rootScope,它不再依赖于您的 DOM 结构。

我知道这不是一个最佳解决方案,因为它污染了全局命名空间,但是我对取决于 DOM 结构的表单名称可见性感到不舒服,以某种意想不到的方式。

于 2015-08-28T11:10:18.090 回答