【问题标题】:Bind JSON object to radio button in angularjs将JSON对象绑定到angularjs中的单选按钮
【发布时间】:2013-04-23 17:52:53
【问题描述】:

所以我试图将单选按钮绑定到对象。我花了大约一个小时试图弄清楚这一点,最后承认失败。这是我得到的:

<table>
        <tr ng-repeat="theCustomer in customers">
            <td>
                <input type="radio" ng-model="currentCustomer" value="theCustomer" id="{{theCustomer.id}}" ng-change="currentCustomer = theCustomer">
                <label for="{{theCustomer.id}}">{{theCustomer.name}}</label>
            </td>
        </tr>
</table>

棱角分明的东西:

bankApp.controller("BankController", function ($scope, CustomerRepository)
{
    $scope.customers = [];
    $scope.currentCustomer = {};
    
    $scope.createCustomer = function () {
        CustomerRepository.save($scope.customer, function (customer) {
            $scope.customers.push(customer);
            $scope.customer = {};
        });
    };
});

目前,当我尝试单击单选按钮时,没有任何反应,甚至没有被选中。我确信必须有一个非常简单的解决方案。最终目标是让currentCustomer 持有反映在收音机选择中的客户。

【问题讨论】:

    标签: angularjs


    【解决方案1】:

    显然,让广播组在 ng-repeat 中工作可能有点棘手。问题在于 ng-repeat 创建了自己的子范围。一种解决方案是将模型绑定到 $parent。 This thread 举个例子。

    我还创建了一个与您的示例更相似的working fiddle

    本质上,我认为您的 html 是唯一需要修改的地方:

    <table>
      <tr ng-repeat="theCustomer in customers">
        <td><input type="radio" ng-model="$parent.currentCustomer" name="foo" value="{{theCustomer}}" id="{{theCustomer.id}}">{{theCustomer.name}}</td>
      </tr>
    </table>
    

    【讨论】:

    • 所以这很有效,唯一的问题是currentCustomer 被设置为字符串化 json 而不是对象。有一个简单的解决方法吗?我试过不带双括号,但没有用。
    • 您希望最终结果看起来像什么?
    • 我真的想通了。 value 属性只接受一个字符串,不能处理一个对象。我进行了重构以适应这一点。谢谢!
    • @CodesLikeA_Mokey 你能发布重构的代码吗?您如何设置默认选择的单选按钮? jsfiddle.net/uNFWW/31
    • @Tushar 看我下面的回答。
    【解决方案2】:

    是因为作用域继承,可以阅读更多关于问题here的内容。

    我在这种情况下使用的一种解决方案是将对象绑定到对象属性,而不是像 ng-model="form.currentCustomer" 这样的原始值。

    演示:Plunker

    【讨论】:

      【解决方案3】:
      <input type="radio" ng-model="$parent.currentCustomer" name="foo" ng-value="theCustomer" id="{{theCustomer.id}}">{{theCustomer.name}}</td>
      

      这里的关键是ng-value="theCustomer。这就是 angular 如何知道选择了哪个对象。 html value 只知道字符串值,不能映射到对象。

      如果您插入上述代码,收音机将反映模型,即使它以编程方式更改。此外,您不能忘记 ng-model 中的 $parent,因为 ng-repeat 创建了一个新范围。

      【讨论】:

        猜你喜欢
        • 2015-04-27
        • 1970-01-01
        • 2014-06-06
        • 2015-10-13
        • 1970-01-01
        • 2016-05-21
        • 1970-01-01
        • 2012-05-18
        • 1970-01-01
        相关资源
        最近更新 更多