字段标签中的角度单选按钮

时间:2019-02-05 07:26:41

标签: angularjs radio-button

我正在使用Angular 1.x提交和处理Web表单,尤其是单选按钮:

<form name="purchaseForm">
     <div class="radio" ng-repeat="i in cancelTypes.data track by $index">
          <label><input type="radio" ng-model="purchaseAction.cancelReasonId" value="{{i.id}}" />{{i.name}}</label>
     </div>
     <button ng-click="purchaseAction()">Save</button>
</form>

在控制器的purchaseAction中,我可以访问通过以下方式选择的选项ID:

this.purchaseAction.cancelReasonId

但是,如果我想要选项的名称或标签而不是ID,该怎么办?以下方法有效,但我不确定这是否是最佳方法:

this.cancelTypes.data[(this.purchaseAction.cancelReasonId-1)].name;

另一种选择是获取ID并向CancelTypes模型发出get请求,但我认为这太过分了?

1 个答案:

答案 0 :(得分:1)

绑定到ng-model的属性是purchaseAction.cancelReasonIdvalue标签的input属性是i.id。这就是为什么您在id中获得cancelReasonId的原因。如果将其更改为i.name,则会获得名称。如果要获取整个对象,则只需在插值语法中传递i。然后,您还必须在JSON.parse上致电purchaseAction.cancelReasonId

尝试一下:

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

    $scope.cancelTypes = {
      data: [{
          id: 1,
          name: '1'
        },
        {
          id: 2,
          name: '2'
        },
        {
          id: 3,
          name: '3'
        },
        {
          id: 4,
          name: '4'
        }
      ]
    };

    $scope.purchaseAction = {
      cancelReasonId: null
    };

    $scope.purchaseActionFn = function() {
      console.log(this.purchaseAction);
      console.log(JSON.parse(this.purchaseAction.cancelReasonId));
    }

  }]);
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>

<div ng-app="app" ng-controller="controller">
  <form name="purchaseForm">
    <div class="radio" ng-repeat="i in cancelTypes.data track by $index">
      <label>
      <input 
        type="radio" 
        ng-model="purchaseAction.cancelReasonId" 
        value="{{ i }}" />
        {{i.name}}
    </label>
    </div>
    <button ng-click="purchaseActionFn()">
    Save
  </button>
  </form>
</div>