AngularJs: Binding ng-model to a list of radio buttons

后端 未结 1 776
温柔的废话
温柔的废话 2021-01-04 02:54

Im trying to bind the selected value in a list of radio buttons to an ng-model

I have:





        
相关标签:
1条回答
  • 2021-01-04 03:14

    The reason behind it is not working is, you are using ng-repeat & you are defining ng-model variable in it. The way ng-repeat works is, it create a new child scope(prototypically inherited) on each iteration of collection. So the ng-model which resides in ng-repeat template, belongs that newly created scope. Here ng-model="selectedOccurrence" create selectedOccurrence scope variable on each iteration of ng-repeat.

    To overcome such a problem you need to follow dot rule while defining model in AngularJS

    Markup

    <body ng-controller="testController">
      <form>
        <div ng-repeat="option in occurrenceOptions track by $index">
          <input type="radio" name="occurrences" ng-value="option" ng-model="model.selectedOccurrence" />
          <label>{{ option }}</label>
        </div>
      </form>
      <div>The selected value is : {{ model.selectedOccurrence }}</div>
    </body>
    

    Code

    $scope.model = {}; //defined a model object
    $scope.model.selectedOccurrence = 'current'; //and defined property in it
    

    Demo Plunkr


    OR Another preferred way would be using controllerAs pattern while declaring controller(use this instead of $scope inside controller).

    HTML

    <body ng-controller="testController as vm">
        <form>
            <div ng-repeat="option in vm.occurrenceOptions">
                <input type="radio" name="occurrence" ng-value="option" ng-model="vm.selectedOccurrence" /><label>{{ option }}</label>
            </div>
        </form>
    </body>
    

    ControllerAs Demo

    0 讨论(0)
提交回复
热议问题