我正在尝试将一些数据从表单发送到我的控制器。在模板文件中用if包围。所以我的工作示例(没有ng-if)是:
看法
<form ng-submit="activate()">
<div class="md-form-group">
<input type="password" name="password" ng-model="input.password" required>
<label>Password</label>
</div>
<button type="submit" class="btn primary btn-block p-x-md">Submit</button>
</form>
控制器
$scope.showDescription1 = false;
$scope.activate = function() {
console.log($scope.input);
return;
...
}
结果
这是我所期望的...带密码字段的模型对象。现在是问题了:当我用ng-if包裹所有视图时,console.log将写入未定义状态。
修改后的视图
<div ng-if="!showDescription1" class="m-b text-sm">
<span>
This is the second description...
</span>
<form ng-submit="activate()">
<div class="md-form-group">
<input type="password" name="password" ng-model="input.password" required>
<label>Password</label>
</div>
<button type="submit" class="btn primary btn-block p-x-md">Submit</button>
</form>
</div>
控制器
(没有变化)
结果
console.log调用将写入未定义的值。我不知道为什么,但是ng-if语句正在清除我的模型?但是为什么呢?
ng-if
当表达式ng-if="!showDescription1"
的计算结果为时true
,会将元素附加到DOM上;当表达式的计算结果为'false'时,将删除该元素。因此,您的任何用户输入都将丢失。
对于您的情况,您需要使用ng-show
或ng-hide
,它们不会重新渲染元素,而是更改其display
。因此,用户输入仍然存在。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句