使用两个带有 angularjs 的 ng-model

use two ng-model with angularjs

这段代码是我写的

<label><input ng-model="filter['category']['auto']" value="auto" type="checkbox" name="category">Auto</label>
<label><input ng-model="filter['category']['music']" value="music" type="checkbox" name="category">Music</label>

在控制器中

$scope.filter = {};

而且我总是使用文件管理器过滤内容。一切正常。但我想使用单选而不是复选框来只允许选择一个类别。我试过这段代码

<label><input ng-model="filter['category'][type]" value="auto" type="radio" name="category" ng-change="type='auto'>Auto</label>
<label><input ng-model="filter['category'][type]" value="music" type="radio" name="category" ng-change="type='music'">Music</label>

但它不起作用。

以后我肯定会做更多的工作来解释你遇到的错误,而不仅仅是说“它不工作”。

但是,您的自动标签中缺少结束符 "。

<label><input ng-model="filter['category']['type']" value="auto" type="radio" name="category" ng-change="type='auto'">Auto</label>

编辑:添加了来自其他答案的 'type' 字符串

要使用单选按钮,两个输入的 ngModel 应该相同。那么就不需要ngChange了。

<label><input ng-model="filter['category']" value="auto" type="radio" name="category">Auto</label>
<label><input ng-model="filter['category']" value="music" type="radio" name="category">Music</label>

有了这个你的 filter 对象看起来像

{ category: 'auto' }

 { category: 'music' }

使用您的原始代码,您最终会得到

{ category: { auto: 'auto', music: 'music' }

假设类别是一个对象。如果不是,您可能会遇到错误。

<label><input ng-model="filter['category']" value="auto" type="radio" name="category" ng-change="type='auto'">Auto</label>
<label><input ng-model="filter['category']" value="music" type="radio" name="category" ng-change="type='music'">Music</label>

这应该可以作为 shown here