[英]Bind JSON object as radio data in AngularJS
I'm trying to solve bind problem in my application. 我正在尝试解决应用程序中的绑定问题。 Similar questions are exists on Stackoverflow, but they do not fully describes my scenario. Stackoverflow上也存在类似的问题,但它们并未完全描述我的情况。
I have an radio group created using repeater. 我有一个使用中继器创建的广播组。 Each style
value is the Object so I'm using ng-value
directive to bind them correct 每个style
值都是Object,因此我使用ng-value
指令将其正确绑定
<label ng-repeat="style in styles">
<input type="radio" ng-model="formData.style" ng-value="style">
{{style.name}}
</label>
And my controller logic is very simple: 我的控制器逻辑非常简单:
var first = {
name: "First Name",
value: "First Value"
};
var second = {
name: "Second Name",
value: "Second Value"
};
var third = {
name: "Third Name",
value: "Third Value"
};
$scope.styles = [first, second, third];
$scope.formData = {};
//this code works and my screen shows 'second' as selected option
$scope.formData.style = second;
//this code do not works and my screen do not show 'Second name' as selected
//$scope.formData.style = {
// name: "Second Name",
// value: "Second Value"
// };
This code works as expected. 此代码按预期方式工作。 I'm setting my selection and form shows selected option. 我正在设置选择,并且表单显示选定的选项。
But in my particular example I don't have reference to my second
value and I need to take this data from third control, so my updated code will looks like: 但是在我的特定示例中,我没有引用second
值,因此我需要从第三个控件中获取此数据,因此更新后的代码如下所示:
$scope.formData.style = {
name: "Second Name",
value: "Second Value"
};
And this behavior do not works - I do not see radio selection on my screen. 而且这种行为不起作用-我在屏幕上看不到收音机选择。
Here is my fiddle https://jsfiddle.net/vadimb/L7uw3oos/3/ 这是我的小提琴https://jsfiddle.net/vadimb/L7uw3oos/3/
The reason here is because you are binding the radio button to the exact property on your model $scope.formData.style
which in the first example is set to second
which is an item within your $scope.styles
array. 这是因为您将单选按钮绑定到模型$scope.formData.style
的确切属性 ,在第一个示例中,该属性设置为second
,这是$scope.styles
数组中的一项。
When you bind your radio button to a new object: 将单选按钮绑定到新对象时:
$scope.formData.style = {
name: "Second Name",
value: "Second Value"
};
You are not binding it to the object that is in the $scope.styles
array, $scope.formData.style
is now it's own completely separate object. 您没有将其绑定到$scope.styles
数组中的对象,而$scope.formData.style
现在是它自己的完全独立的对象。
If you want to set it dynamically, you must lookup the item you want from within $scope.styles
. 如果要动态设置,则必须在$scope.styles
查找所需的项。
$scope.formData.style = _.findWhere($scope.styles, { name: "Second Name"})
function getFromArray(array, value) {
for(var i = 0; i < array.length; i++) {
if (array[i].name.toLowerCase() == value.toLowerCase()) {
return array[i];
}
}
}
$scope.formData.style = getFromArray($scope.styles, "Second Name");
Although I'd recommend using some sort of Id instead of a magic string. 尽管我建议您使用某种Id代替魔术字符串。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.