使用angular.js用最后选择的值填充隐藏字段
Populate hidden field with the last selected value using angular.js
那么,我的代码是Fiddle
<div ng-app="testApp">
<div ng-controller="MainCtrl">
<form>
<p>
<select ng-model="selectedItem" ng-options="i.name for i in items"></select>
</p>
<p ng-show="selectedItem.subItems">
<select ng-model="selectedSubItem" ng-options="i.name for i in selectedItem.subItems"></select>
</p>
<p ng-show="selectedSubItem.subItems">
<select ng-model="selectedSubSubItem" ng-options="i.name for i in selectedSubItem.subItems"></select>
</p>
<input type="hidden" name="selection" value="????">
<input type="submit" value="submit">
</form>
</div>
在这段代码中,我只在所选项有子数组时才显示下一个下拉列表。现在,我想使用Angular.js用下拉链的最后一个选择值填充隐藏字段的值。
换句话说,如果用户在最后出现的下拉框中选择了一个选项,我希望最后的隐藏字段具有该值,以便与表单一起提交。
我该怎么做呢?
您可以使用:
<input type="hidden" name="selection" value="{{selectedSubSubItem.name}}">
一旦各自的select
的值发生变化,双向绑定将更新隐藏输入的值。
如果你想根据最后一次选择动态获取它:
<input type="hidden" name="selection" value="{{selectedSubSubItem.name || selectedSubItem.name || selectedItem.name}}">
如果你想回到链条,这将有助于。但我强烈建议将此逻辑移动到控制器:
<input type="hidden" name="selection" value="{{(selectedSubItem.subItems ? selectedSubSubItem.name : false) || (selectedItem.subItems ? selectedSubItem.name : false) || selectedItem.name}}">
如果链的长度是固定的,可以这样做:
<input type="hidden" name="selection"
value="{{ (selectedSubSubItem || selectedSubItem || selectedItem).name }}"/>
要解决回溯链的问题,一个简单的解决方案是使用ng-change
并使所有下一个值无效,即:
<select ng-model="selectedItem" ng-options="i.name for i in items"
ng-change="selectedSubItem=null;selectedSubSubItem=null"></select>
参见fork fiddle: http://jsfiddle.net/zH77p/1/
替代ng-change
,可以使用手表在范围内;这样做的好处是,这些表只需要知道它们的直接子节点:
$scope.$watch("selectedItem", function(newval, oldval) {
if( newval !== oldval ) $scope.selectedSubItem = null;
});
$scope.$watch("selectedSubItem", function(newval, oldval) {
if( newval !== oldval ) $scope.selectedSubSubItem = null;
});
由于您对这种类型的"链式选择"感兴趣,因此需要使用一些更复杂的逻辑。小提琴在这里:http://jsfiddle.net/2Az4P/3/我使用的是ng-value,但是你可以保留你的值并将其设置为
value="{{choiceValue()}}
也有同样的效果。我所做的是将答案放在一个数组(selectedItem = []
)中,然后在进行过程中填充它(注意每个选择的ng-model
)。
在每次选择时,使用choiceValue()
函数更新相应的值,该函数相应地更新ng-value
。
这样,你可以添加尽可能多的选择链,只是更新他们的数量(实际上,你可以使用ng-repeat
,并使用$index
来自动创建更多的选择级别)。
这是更多的工作,但你可以在这里看到基本的:http://jsfiddle.net/brendanowen/uXbn6/8/
这完全取决于你需要多复杂/自动化来做这件事:)
- 如何隐藏和显示通过窗体填充的表
- 隐藏 DIV 标签,直到填充所有文本字段
- Chrome通过自动填充隐藏背景图像
- 使用数据中的值填充隐藏输入
- jQuery 获取输入值以检索匹配的数组值以填充隐藏的输入
- JQuery 获取动态值并填充隐藏的表单字段
- 使用 Js 从选择菜单填充隐藏的输入字段
- 填充隐藏字段Microsoft JScript 运行时错误:对象不支持此属性或方法
- html页面自动提交-javascript填充隐藏字段
- select onChange事件触发javascript,从数组值中填充隐藏的Input值
- 如何填充隐藏的元素
- jQuery-用列表数据填充隐藏字段的最佳方式
- 从codeehind填充隐藏字段,然后将其作为QueryStringASP/javascript传递回codeehind
- 如何从url参数中填充隐藏的输入文本字段
- 自动填充隐藏表单字段与返回值从javascript
- 用h1标签或URL填充隐藏字段
- jQuery克隆元素,然后用连接的结果填充隐藏字段,以避免空列表问题
- 使用angular.js用最后选择的值填充隐藏字段
- 从其他文本字段 JavaScript 填充隐藏字段
- 用自动完成值填充隐藏字段