Multiple ng-models on one input field?

徘徊边缘 提交于 2019-12-03 07:20:53

问题


I have a form, and a list of items. I used ng-model="searchFor" to filter out the list of items appropriately (this part is working fine), but I also want to "submit" the item that's filtered out -- which would require ng-model="adding_item.name" on the input field as well (I think).

Can you have multiple ng-models on one input field? Is there another way around this?


回答1:


Try using ng-change event to capture model value and assign it to other input element with its own ng-model.

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app>
  <input type="text" ng-model="input" ng-change="input1=input;input2=input; " />
  <input type="hidden" ng-model="input1" />
  <input type="hidden" ng-model="input2" />
  <br>Model
  <br>{{input | uppercase}}
  <br>Model 1
  <br>{{input1 | uppercase}}
  <br>Model 2
  <br>{{input2 | uppercase}}
</div>



回答2:


No, ngModel wasn't supposed to do things like this, at this point it is better to start relocating the logic from the view. For this scenario you could make use of getterSetter option:

https://docs.angularjs.org/api/ng/directive/ngModel#binding-to-a-getter-setter

It is hard to make substantial suggestions without seeing the code.



来源:https://stackoverflow.com/questions/29448097/multiple-ng-models-on-one-input-field

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!