gpt4 book ai didi

javascript - 需要默认选择一个 Angular JS 单选按钮

转载 作者:太空狗 更新时间:2023-10-29 15:32:17 24 4
gpt4 key购买 nike

我是 Angular JS 的新手,我正在尝试创建一组单选按钮。创建按钮是简单的部分,但我在弄清楚如何默认选择其中一个按钮而不破坏所有内容时遇到问题。我已经阅读了有关在 Angular 文档中使用 ngChecked 以及其他多个 stackoverflow 问题的信息,但似乎仍然不太明白。

我需要做的是在用户访问页面时预先选择其中一个描述。价格、折扣和交易值(value)也需要与预选的 price_option 对象中的值一起显示。

这是我要开始工作的代码:http://jsfiddle.net/qWzTb/311/

HTML代码:

<body ng-app="demoApp">
<div ng-controller="DemoController" ng-init="init([{qty: 1, price:10, qty_description:'descrip 1', discount:'1%', deal_value:200}, {qty: 2, price:7, qty_description:'descrip 2', discount:'5%', deal_value:100}])">

<div>
<label ng-repeat="price_option in price_options">
<input type="radio" ng-model="init.price_option" ng-value="price_option" ng-checked="selected_price_option" name="quantity"/>
{{ price_option.qty_description }}
</label>
<ul>
<li>{{ init.price_option.price }}</li>
<li>{{ init.price_option.discount }}</li>
<li>{{ init.price_option.deal_value }}</li>
</ul>
</div>
</div>
</body>

Javascript:

angular.module('demoApp', []).controller('DemoController', function($scope) {

$scope.init = function(prices) {
$scope.price_options = prices;
$scope.selected_price_option = $scope.price_options[0];
};
});

最佳答案

HTML

<body ng-app="demoApp">
<!-- ng-init functionality belongs in controller -->
<div ng-controller="DemoController">
<!-- move ng-repeat to container div instead of label -->
<div ng-repeat="price_option in price_options">
<label>
<!-- the model is the scope variable holding the selected value -->
<!-- the value is the value of this particular option -->
<input type="radio" ng-model="$parent.selected_price_option" ng-value="price_option" name="quantity" />{{price_option.qty_description}}</label>
<ul>
<li ng-bind="price_option.price"></li>
<li ng-bind="price_option.discount"></li>
<li ng-bind="price_option.deal_value"></li>
</ul>
</div>
</div>
</body>

JS

angular.module('demoApp', []).
controller('DemoController', function ($scope) {
//moved init logic to controler
$scope.price_options = [{
qty: 1,
price: 10,
qty_description: 'descrip 1',
discount: '1%',
deal_value: 200
}, {
qty: 2,
price: 7,
qty_description: 'descrip 2',
discount: '5%',
deal_value: 100
}];
$scope.selected_price_option = $scope.price_options[1];
});

fork fiddle :http://jsfiddle.net/W8KH7/2/

或者您可以使用对象策略来避免必须引用 $parent: http://jsfiddle.net/W8KH7/3/

关于javascript - 需要默认选择一个 Angular JS 单选按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22846693/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com