如何从单选按钮获取数据? angularjs

时间:2014-08-23 07:05:29

标签: angularjs

我得到所选单选按钮的价格和名称。简单的html标签很简单。 但是当我尝试通过数组(项目)中的angularjs生成单选按钮时,我堆叠了

帮助!

http://jsfiddle.net/hanze/j9x23apu/

HTML

<h1>Select </h1>

<div ng-app="" ng-controller="OrderCtrl">
      <div ng-repeat="item in items">
<div class="radio">
<label>
     <input type="radio" name="item" ng-model="item" ng-checked="{{item.checked}}"> 
     {{item.name}} +{{item.price}} $.</label>
</div>
</div>

Your choice: {{}} **what i must write here?**
<br>
Price: {{}} **and here?**
</div>

JS

 OrderCtrl = function ($scope) {
$scope.items = [{
name: 'None',
value: "no",
price: 0,
checked: true
}, {
name: 'Black',
value: "black",
price: 99,
checked: false
}, {
name: 'White',
value: "white",
price: 99,
checked: false
}, {
name: 'Barhat',
value: "barhat",
price: 49,
checked: false
}, {
name: 'Barhat',
value: "cream",
price: 49,
checked: false
}]

3 个答案:

答案 0 :(得分:1)

您可以查看有关单选按钮here的angularjs文档。你不需要在这里使用ng-checked。选择redio时,使用ng-value设置值。 我更改了您的jsfiddle帖子。

答案 1 :(得分:0)

您缺少输入的结束标记。当你有重复时,你有一个单独的范围。在这种情况下,您需要$ parent.selectedItem来保存您选择的元素。

我已使用工作状态解决方案更新了JSFiddle

<div ng-app="" ng-controller="OrderCtrl">
<div ng-repeat="item in items" style="text-indent: 30px">
     <input type="radio" name="itemRadio"  ng-model="$parent.selectedItem" ng-value="item.name"/>
    {{item.name + '-' + item.price}}$.
</div>
    Your choice: {{selectedItem}}
</div>

答案 2 :(得分:0)

jsFiddle:http://jsfiddle.net/j9x23apu/16/

HTML

<div ng-app="" ng-controller="OrderCtrl">
    <div ng-repeat="item in items" style="text-indent: 30px">
        <label>
            <input type="radio" name="item" ng-checked="{{item.checked}}" ng-click="change_item($event)" item-name="{{item.name}}" item-price="{{item.price}}" /> {{item.name}} + {{item.price}} 
        </label>
    </div>

    Your choice: {{selectedName}}
    <br />
    Price: {{selectedPrice}}
</div>

JS

OrderCtrl = function ($scope) {
$scope.change_item = function(e) {
    $scope.selectedName = e.target.attributes['item-name'].value;
    $scope.selectedPrice = e.target.attributes['item-price'].value;
};

$scope.items = [{
    name: 'None',
    value: "no",
    price: 0,
    checked: true
}, {
    name: 'Black',
    value: "black",
    price: 99,
    checked: false
}, {
    name: 'White',
    value: "white",
    price: 99,
    checked: false
}, {
    name: 'Barhat',
    value: "barhat",
    price: 49,
    checked: false
}, {
    name: 'Barhat',
    value: "cream",
    price: 49,
    checked: false
}]
}