如何将单选按钮标记为选中Angular with ng click/ng change

How to mark a radio button as checked in Angular with ng-click / ng-change?

本文关键字:ng with Angular click change 单选按钮 记为      更新时间:2023-09-26

http://plnkr.co/edit/rXWUUjLtJi79z2hF1uVX?p=preview

我有一个非常简单的plnkr,基本上当单击li元素时,我希望选中单选按钮。

以下是如何实现的?现在没有收音机被选中。

如果我删除了ng点击,那么用户可以只点击单选按钮,但如果用户点击li内部的文本/标签,我也希望选择单选按钮,这就是为什么我试图让li上的ng-click以这种方式工作。


angular.module('app', [])
.controller('mainController', ['$scope', '$rootScope',
                              function($scope,$rootScope) {
                                
  $scope.toggleTags = function(type) {
    console.log(type);
    switch(type) {
      case 'watchlist':
        $scope.watchlist = true;
        $scope.private   = false;
        break;
      case 'private':
        $scope.watchlist = false;
        $scope.private   = true;
        break;
    }
  };
  
}]);
body { font-family: Arial, sans-serif; }
li {
  margin: 10px;
  list-style: none;
  width: 100%;
  clear: both;
  cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="app" ng-controller="mainController">
      
    <ul>
        <li ng-click="toggleTags('watchlist')">
          <input type="radio"
                 name="personalGroup"
                 ng-model="watchlist"
                 ng-change="toggleTags('watchlist')"
                 value="watchlist">
                 My Watchlist
        </li>
        <li ng-click="toggleTags('private')">
          <input type="radio"
                 name="personalGroup"
                 ng-model="private"
                 ng-change="toggleTags('private')"
                 value="private">
                 My Private Tags
        </li>
    </ul>
    
  </body>

对于这个示例,我不会使用ng-click来执行此操作。相反,我会使用HTMLDOM对象<label for="radio_button_id_here">

HTML

<li>
  <input type="radio" name="personalGroup" ng-model="watchlist" value="watchlist" id="watchlist">
  <label for="watchlist">My Watchlist</label>
</li>
<li>
  <input type="radio" name="personalGroup" ng-model="private" value="private" id="private">
  <label for="private">My Private Tags</label>
</li>