Javascript 如何将select与现有模型绑定
我有Javascript 如何将select与现有模型绑定,javascript,angularjs,Javascript,Angularjs,我有select和现有的选项,我需要将select中的值绑定到我的模型 我所做的: <select ng-model="site.id"> <option value="1">First<option> <option value="2">Second<option> </select> 弗斯特 第二 其中我的模型是:user=['name':'andry','site':{'id':1,name:'F
select
和现有的选项
,我需要将select中的值绑定到我的模型
我所做的:
<select ng-model="site.id">
<option value="1">First<option>
<option value="2">Second<option>
</select>
弗斯特
第二
其中我的模型是:user=['name':'andry','site':{'id':1,name:'First'}]
我想将此选择与我的模型绑定。怎么可能呢?当前,在从中选择值后,将更新选择站点id,但站点名称-不更新
我是angular的新手。您可以使用angular的$watch功能
$scope.$watch("site.id", function(){
var new_id = $scope.site.id;
// so you now new id change site name
$scope.site.name = "asdfasdfasdf"
});
阅读请使用ng选项使用select: 查看:
<body ng-controller="MainCtrl">
<h1>Select something below</h1>
<select id="s1" ng-model="selectedItem" ng-options="item as item.name for item in items"></select>
<h3>The selected item:</h3>
<pre>{{selectedItem}}</pre>
</body>
<select ng-model="site">
<option ng-repeat="item in items" value="{{item}}"
ng-selected="site === item">{{item.name}}<option>
</select>
下一步见
$scope.selectedItem
包含$scope.items
数组中的完整对象。使用带有ng repeat的选项也可以:
将模型和值指定为对象
{{item.name}
为什么不使用ng选项@实际上,ArtyomPranovich是从服务器端渲染的选项,因此它们是预定义的。有没有办法,如何从select中获取选项?请看我的答案。感谢您的回答,还有一个问题:如何从choosen选项中获取值?您可以通过访问$scope来实现,就像在answeroptions中一样。选项是从服务器端预渲染的,而不是从angular中预渲染的,是否可以从select中获取选项?@fuserthrower,拜托,在watcher:)中为site.id添加非“未定义”的检查@fuserthrower,不完全是我要查找的内容。接受的答案看起来更具角度感。我已经从服务器端预先呈现了选项。
<select ng-model="site">
<option ng-repeat="item in items" value="{{item}}"
ng-selected="site === item">{{item.name}}<option>
</select>