2016-04-14 83 views
1

我有2个单选按钮。我想为每个单选按钮绑定不同的属性。例如:选择单选按钮时,可以绑定不同的值吗?

<label> 
    Foo 
    <input type="radio" name="test" value="foo"/> 
</label> 
<label> 
    Bar 
    <input type="radio" name="test" value="bar"/> 
</label> 
  • 无线电富具有值 “标识”: “ID1”, “值”: “富”
  • 无线电酒吧值: “ID”: “ID2”, “价值”: “酒吧”

而且到<p>的结合应该是这样的:

<p>The id for selected radio is {{ radio.id }}, and value for it is {{ radio.value }}</p> 

在“结果选定无线电ID是ID1,和价值是FO o“

回答

0

是的。您可以为每个单选按钮创建一个对象,并为对象分配id和value属性。

例子:https://jsfiddle.net/x9nfke0d/

角:

function Controller() { 
    var vm = this; 

    vm.selected_radio = null; 
    vm.foo = { 
     id: 1, 
     value: 'Foo' 
    }; 
    vm.bar = { 
     id: 2, 
     value: 'Bar' 
    }; 
    vm.setRadio = setRadio; 

    function setRadio(obj) { 
     vm.selected_radio = obj; 
    } 
} 

HTML:

<label> 
    Foo 
    <input type="radio" name="test" ng-click="ctrl.setRadio(ctrl.foo)"> 
</label> 
<label> 
    Bar 
    <input type="radio" name="test" ng-click="ctrl.setRadio(ctrl.bar)"> 
</label> 

你可以走得更远了一步,创造无线电对象的数组,然后重复他们在一个NG-重复。

+0

谢谢你,先生。这项工作如预期。 ng-if对我来说是无用的,因为我需要显示选择不重要,如果选择或不,所以我只是从我的代码中删除它。 拯救生命! –

0

工作小提琴Here

var myApp = angular.module('myApp', []); 
 
myApp.controller('MyCtrl', ['$scope', function($scope) { 
 
    $scope.foo = {bar:"foo"}; 
 
}]);
<section ng-controller="MyCtrl"> 
 
{{foo.bar}} 
 
<label>Foo<input ng-model="foo.bar" type="radio" name="test" value="foo"/></label> 
 
<label>Bar<input ng-model="foo.bar" type="radio" name="test" value="bar"/></label> 
 
</section>

+0

无法使用我的重新创建此代码:( –

相关问题