我遇到了一个问题,当ng表单嵌套在ng范围内时,它没有在范围上设置表单。
例如
<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')
}
}
}
对此有什么解决办法吗?测试小提琴可以在这里找到
ng开关创建一个子作用域,并在此作用域上创建表单。因此,子作用域窗体在父作用域上不可用。
要访问它,可以像ng-click=test(nixTest)
一样将它传递给方法test()
。因此,还需要更新scope方法签名以支持输入参数。
我遇到了同样的问题。不幸的是,我无法轻松应用Chandermani的解决方案,因为我需要在ng-switch
父作用域内从$on
调用访问表单名称。因此,我创建了一个指令,将表单的名称发送到$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结构的表单名称可见性感到不舒服,这有点出乎意料。