带有ng-repeat的单选按钮并不总是初始化

时间:2015-09-16 14:33:15

标签: angularjs

我希望在单击其他按钮时在运行时修改单选按钮列表。修改了单选按钮列表后,默认情况下应始终选择列表的第一个单选按钮。 另外,某些div的可见性取决于当前选择的单选按钮。

以下是plunker http://plnkr.co/edit/KlMCg3JmT43boP0JwU7R (请参阅更新)

所以我有一个单选按钮列表:

<body ng-app="app" ng-controller="ctrl">
<div class="btn-group">
    <li ng-repeat="item in currentSpecificTypes">
      <a href="" ng-click="specificTypeSelected($index)">{{item.label}}</a>
    </li>
    <label ng-repeat="item in currentPeriodTypes" class="radio-inline"><input type="radio" name="optPeriod" ng-click="periodSelected($index)" ng-value="$index" ng-model="selectedPeriod">{{item.label}}</label>
</div>

<div ng-show="selectedPeriod == 0">0</div>
<div ng-show="selectedPeriod == 1">1</div>
<div ng-show="selectedPeriod == 2">2</div>

单击其中一个li时,将修改列表(currentPeriodTypes)。指数为&#34; 0&#34;应该默认选择:

angular.module("app", [])
.controller("ctrl", ["$scope", function($scope)
{
$scope.periodTypes = [
  {label:"Hours", value: 0},
  {label: "Morning", value: 1},
  {label: "Afternoon", value: 2},
  {label: "Day", value: 3}
];

$scope.currentSpecificTypes = [
  {label: "type1", hourAllowed: false, morningAllowed: true, afternoonAllowed: true, dayAllowed: true},
  {label: "type2", hourAllowed: false, morningAllowed: false, afternoonAllowed: true, dayAllowed: true},
  {label: "type3", hourAllowed: false, morningAllowed: true, afternoonAllowed: false, dayAllowed: true}
  ];

$scope.specificTypeSelected = function (stIndex)
{

    $scope.selectedSpecificType = stIndex;

    $scope.currentPeriodTypes.length = 0;
    if ($scope.currentSpecificTypes[stIndex].hourAllowed) $scope.currentPeriodTypes.push($scope.periodTypes[0]);
    if ($scope.currentSpecificTypes[stIndex].morningAllowed) $scope.currentPeriodTypes.push($scope.periodTypes[1]);
    if ($scope.currentSpecificTypes[stIndex].afternoonAllowed) $scope.currentPeriodTypes.push($scope.periodTypes[2]);
    if ($scope.currentSpecificTypes[stIndex].dayAllowed) $scope.currentPeriodTypes.push($scope.periodTypes[3]);

    $scope.periodSelected(0);
};

$scope.periodSelected = function (index)
{
    $scope.selectedPeriod = index;
    alert(index);
};

$scope.dateSelected = function (date) {
};


$scope.currentPeriodTypes = [];

}]);

因此,尽管$ scope.periodSelected(0),当点击li并播放无线电时,默认情况下没有选择单选按钮。

更新 我提供的第一个plunker缺少ng-model属性。我的错。 这是更正后的版本http://plnkr.co/edit/DedNOrpwzwKhRYvKdHcf?p=preview 当选择Type 1,然后选择Type 2,然后选择Type 3,实际上每次都可以看到第一个单选按钮。但是当我选择&#34;输入1&#34;,然后&#34;下午&#34;,然后&#34;输入2&#34;时,不再预先选择任何选项。这是我无法解决的问题。

1 个答案:

答案 0 :(得分:0)

单选按钮无法正常工作,因为ng-repeat会创建子范围。

Demo

<input type="radio" ng-value="$index" ng-model="$parent.selectedPeriod">