What is difference in ways of setting radio button checked=true in AngularJS

情到浓时终转凉″ 提交于 2020-01-06 18:44:21

问题


If I set radio button default selection using ng-checked="$first" then it got checked. If I use ng-checked="true" radio button doesn't get checked?

Kindly explain when this can happen?

I cant use $first acc to my Use case


回答1:


One thing to note about radio buttons once you check they cant be unchecked. You must have to provide another options. I prepared some samples for you.

In 1st method eventhough i set the value to true in controller and set the value to 1 it got checked.this is the most optimal solution.

2nd method using ng-checked eventhough i change the value but ng-model values are not updated. so you have to use ng-change function and track every ng-model.personally nobody like this method.

var app = angular.module('myApp', []);

app.controller('MainCtrl', function ($scope) {
  $scope.myradio = true;
  $scope.myradio_ng1 = true;
  $scope.myradio_ng2 = false;
  
  $scope.first = true; // probably you are getting this from db
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<title>Radio</title>
</head>
<body ng-controller="MainCtrl">
  <p>1. Using ng-model</p>
  <div>
    <label for="myradio1">Yes</label>
    <input type="radio" ng-model="myradio" name="myradio" id="myradio1" value="1" />
    <label for="myradio2">No</label>
    <input type="radio" ng-model="myradio" name="myradio" id="myradio2" value="0"/>
  </div>
  <div>Radio value: {{myradio}}</div>
  <p>2. Using ng-checked</p>
  <div>
    <label for="myradio3">First</label>
    <input type="radio" name="myradiong" id="myradio3" ng-checked="myradio_ng1" />
    <label for="myradio4">Second</label>
    <input type="radio" name="myradiong" id="myradio4" ng-checked="myradio_ng2"/>
    <div>Radio value for first: {{myradio_ng1}}</div>
    <div>Radio value for Second: {{myradio_ng2}}</div>
  </div>
  
  <p>Your case</p>
  <label for="first">First</label>
  <input type="radio" id="first" ng-checked="first" />
</body>
</html>

In your case you have an element you want to checked when it is true. In your controller set the value of $scope.first to true or false then in your view use ng-checked="first". Find the result by running the code snippet.



来源:https://stackoverflow.com/questions/42050537/what-is-difference-in-ways-of-setting-radio-button-checked-true-in-angularjs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!