我正在尝试初始化/选择组内的特定单选按钮。我想将索引号传递给名为“selected-item”的属性。
<div class="top">
<radio-buttons model="colour" selected-item="1" items='colours'></radio-buttons>
<div>{{colour}}</div>
</div>
<div class="center">
<radio-buttons model="day" selected-item="2" items='days'></radio-buttons>
<div>{{day}}</div>
</div>
<div class="bottom">
<radio-buttons model="phone" selected-item="3" items="phones"></radio-buttons>
<div>{{phone}}</div>
</div>
directives.directive('radioButtons', function () {
return {
restrict: 'E',
scope: {
model: '=',
items: '=',
selectedItem: '@'
},
templateUrl: 'template/radio-group.html',
link: function(scope) {
console.log(scope.selectedItem);
scope.onItemChange = function(item) {
console.log(item);
scope.model = item;
};
}
};
});
<div ng-repeat='item in items'>
<input
type="radio"
name="{{item.group}}"
ng-value="{{item.value}}"
ng-model="model"
ng-change="onItemChange(item)"/>
{{item.text}}
</div>
$scope.colours= [ {
text: "Pink",
value: 5,
group: "colourGroup",
img: 'app/img/icon.jpg'
}, {
text: "Yellow",
value: 6,
group: "colourGroup",
img: 'app/img/icon.jpg'
}, {
text: "Blue",
value: 7,
group: "colourGroup",
img: 'app/img/icon.jpg'
}, {
text: "Green",
value: 8,
group: "colourGroup",
img: 'app/img/icon.jpg'
}
];
$scope.days = [ {
text: "Monday",
value: 9,
group: "dayGroup"
}, {
text: "Tuesday",
value: 10,
group: "dayGroup"
}, {
text: "Wednesday",
value: 11,
group: "dayGroup"
}, {
text: "Thursday",
value: 12,
group: "dayGroup"
}
];
$scope.phones = [ {
text: "Android",
group: "phoneGroup",
value: 13
}, {
text: "iOS",
group: "phoneGroup",
value: 14
}, {
text: "Blackberry",
group: "phoneGroup",
value: 15
}];
任何帮助都会很棒!
干杯。
答案 0 :(得分:2)
尝试将ng-value="{{item.value}}"
更改为value="{{item.value}}"
。
然后将ng-checked="$index == (selectedItem - 1)"
添加到模板中的输入中。
或者:ng-checked="$index == (selectedItem - 1) || $first"
或$last
,如果您希望在尝试超出范围的索引时选择某些内容。
答案 1 :(得分:0)
不使用价值,这是另一种解决方案:
link: function(scope) {
scope.model = angular.copy(scope.items[scope.selectedItem -1]);
var setSelected = function(v) {
var i = 0;
for(; i < scope.items.length;i++) {
if(scope.items[i].value === v) {
return scope.items[i];
}
}
}
scope.$watch('model.value',function(v) {
//because the value is out of sync with the model, have to reset the model
scope.model = angular.copy(setSelected(v));
});
}
请注意,ng-value必须是字符串,因此必须是ng-model。 scope.model仅作为指令中的范围公开,因此使用scope.model.value
<div ng-repeat='item in items'>
<input
type="radio"
name="{{item.group}}"
ng-value="{{item.value}}"
ng-model="model.value" />
{{item.text}}
</div>