我ngForm
- 嵌套在ngRepeat
中。表单绑定到页面控制器上的变量。然后使用ngIf
基于选项卡的活动索引将表单添加到DOM或从DOM中删除。
奇怪的是,如果我按升序激活制表符,表单将正确绑定到控制器的表单变量,但如果我按降序激活制表符,则表单不受约束。
angular.module("myApp", [])
.controller("MyController", function($scope) {
var ctrl = this;
ctrl.index = 0;
ctrl.tabs = [1, 2, 3, 4, 5];
ctrl.text = null;
ctrl.setIndex = function(index) {
ctrl.index = index;
};
});

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular.min.js"></script>
<body ng-app="myApp">
<div ng-controller="MyController as ctrl">
{{ctrl.form ? "Form is bound!" : "Form is NOT bound." }}
<div ng-repeat="item in ctrl.tabs">
<ng-form name="ctrl.form" ng-if="ctrl.index===$index">
<input type="text" ng-attr-name="{{item+'-test'}}" ng-model="ctrl.text" required/>
</ng-form>
</div>
<ul>
<li><a href="#" ng-click="ctrl.setIndex(0)">1</a></li>
<li><a href="#" ng-click="ctrl.setIndex(1)">2</a></li>
<li><a href="#" ng-click="ctrl.setIndex(2)">3</a></li>
<li><a href="#" ng-click="ctrl.setIndex(3)">4</a></li>
<li><a href="#" ng-click="ctrl.setIndex(4)">5</a></li>
</ul>
</div>
</body>
&#13;
任何人都知道为什么会这样?
答案 0 :(得分:1)
我不知道为什么表单是从控制器解除绑定的(这必须归因于ng-repeat
内部)。
但是,如果将每个表单绑定到不同的名称,即:
<ng-form name="ctrl.form{{item}}" ng-if="ctrl.index===$index">
并定义一个访问它的简单方法:
ctrl.currentForm = function() {
return ctrl['form' + ctrl.tabs[ctrl.index]];
};
然后一切都按预期工作。
angular.module("myApp", [])
.controller("MyController", function($scope) {
var ctrl = this;
ctrl.index = 0;
ctrl.tabs = [1, 2, 3, 4, 5];
ctrl.text = null;
ctrl.currentForm = function() {
return ctrl['form' + ctrl.tabs[ctrl.index]];
};
ctrl.setIndex = function(index) {
ctrl.index = index;
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular.min.js"></script>
<body ng-app="myApp">
<div ng-controller="MyController as ctrl">
{{ctrl.currentForm() ? "Form is bound in tab with index " + ctrl.index + "!" : "Form is NOT bound." }}
<div ng-repeat="item in ctrl.tabs">
<ng-form name="ctrl.form{{item}}" ng-if="ctrl.index===$index">
<input type="text" ng-attr-name="{{item+'-test'}}" ng-model="ctrl.text" required/>
</ng-form>
</div>
<ul>
<li><a href="#" ng-click="ctrl.setIndex(0)">1</a></li>
<li><a href="#" ng-click="ctrl.setIndex(1)">2</a></li>
<li><a href="#" ng-click="ctrl.setIndex(2)">3</a></li>
<li><a href="#" ng-click="ctrl.setIndex(3)">4</a></li>
<li><a href="#" ng-click="ctrl.setIndex(4)">5</a></li>
</ul>
</div>
</body>