Javascript AngularJS选择-在控制器中设置ng模型不会更新所选值
我在升级选择中的ng型号时遇到问题。Javascript AngularJS选择-在控制器中设置ng模型不会更新所选值,javascript,angularjs,user-interface,data-binding,local-storage,Javascript,Angularjs,User Interface,Data Binding,Local Storage,我在升级选择中的ng型号时遇到问题。 我有以下HTML: <div ng-app> <div ng-controller="Ctrl"> <select ng-model="viewmodel.inputDevice" ng-options="i.label for i in viewmodel.inputDevices"> </select> </div> </di
我有以下HTML:
<div ng-app>
<div ng-controller="Ctrl">
<select ng-model="viewmodel.inputDevice"
ng-options="i.label for i in viewmodel.inputDevices">
</select>
</div>
</div>
您可以使用以下命令
我要做的是将inputDevice中的值放入集合inputDevices中的第一个设备中
我知道我可以传递elem1,它将工作,但我不能这样做,因为我想将选择保存在本地存储中,然后将其恢复到ng模型对象。任何建议都将不胜感激
谢谢:
self.inputDevice = {
value: '1',
label: 'input1'
};
我只存储索引:
self.inputDevice = 0; // or 1 - second item
以及:
{{i.label}
这条路行得通
修复了演示您可以存储值而不是Maxim演示的对象,或者您可以从
inputDevices
数组中提取正确的值,方法如下:
self.inputDevice = self.inputDevices.filter(function(item) {
return item.value == storedValue.value;
})[0];
根据原始问题中的代码适用于我:
{{viewmodel.inputDevice}
毫无疑问,您的js代码可以正常工作,但viewmodel的构建可能会简单一些:
函数Ctrl($scope){
//视图模型
$scope.viewmodel={inputDevices:[
{值:'1',标签:'input1'},
{值:'2',标签:'input2'}
]};
$scope.viewmodel.inputDevice=$scope.viewmodel.inputDevices[0];
}
jsfiddle感谢您的回答,它很有帮助,但是它不太适合我的需要,因为我需要保存all对象并依赖其键而不是索引,因为inputDevices集合是动态更改的。
<select>
<option ng-repeat="i in viewmodel.inputDevices"
value="{{i.label}}"
ng-selected="viewmodel.inputDevices.indexOf(i) == viewmodel.inputDevice"
>{{i.label}}</option>
</select>
self.inputDevice = self.inputDevices.filter(function(item) {
return item.value == storedValue.value;
})[0];