繁体   English   中英

在AngularJS中将JSON对象绑定为广播数据

[英]Bind JSON object as radio data in AngularJS

我正在尝试解决应用程序中的绑定问题。 Stackoverflow上也存在类似的问题,但它们并未完全描述我的情况。

我有一个使用中继器创建的广播组。 每个style值都是Object,因此我使用ng-value指令将其正确绑定

        <label ng-repeat="style in styles">
            <input type="radio" ng-model="formData.style" ng-value="style">
            {{style.name}}
        </label>

我的控制器逻辑非常简单:

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"
//    };

此代码按预期方式工作。 我正在设置选择,并且表单显示选定的选项。

但是在我的特定示例中,我没有引用second值,因此我需要从第三个控件中获取此数据,因此更新后的代码如下所示:

$scope.formData.style = {
   name: "Second Name",
   value: "Second Value"
};

而且这种行为不起作用-我在屏幕上看不到收音机选择。

这是我的小提琴https://jsfiddle.net/vadimb/L7uw3oos/3/

这是因为您将单选按钮绑定到模型$scope.formData.style确切属性 ,在第一个示例中,该属性设置为second ,这是$scope.styles数组中的一项。

将单选按钮绑定到对象时:

$scope.formData.style = {
    name: "Second Name",
    value: "Second Value"
};

您没有将其绑定到$scope.styles数组中的对象,而$scope.formData.style现在是它自己的完全独立的对象。

如果要动态设置,则必须在$scope.styles查找所需的项。

使用下划线:

$scope.formData.style = _.findWhere($scope.styles, { name: "Second Name"})

使用纯JS:

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");

尽管我建议您使用某种Id代替魔术字符串。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM