简体   繁体   中英

how to select the radio buttons dynamically using JSON in angular js

This is my html code

<!DOCTYPE html>
<html>
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
    <body>

    <div ng-app="myApp" ng-controller="myCtrl">

    First Name: <input type="text" ng-model="firstName"><br>
    Last Name: <input type="text" ng-model="lastName"><br>
    <br>
    Full Name: {{firstName + " " + lastName}}

    <div ng-repeat="data in tdata">
        <div>
        {{data.name}} : yes:<input type="radio" name={{data.name}}/> &nbsp No:<input type="radio" name={{data.name}}/> <br/>
        </div>
    </div>

    </div>
    </body>
    </html>

and this is my js

<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
    $scope.firstName = "John";
    $scope.lastName = "Doe";
    $scope.tdata = [
                    {"name":"Santhosh", "status": 1},
                    {"name":"Eswar", "status": 0},
                    {"name":"Kishore", "status": 1},
                    {"name":"Gnani", "status": 0}
    ]
    console.log($scope.tdata);
});
</script>

In the JSON there is one field called status. So what I need is if the status is 0, no should be chosen and if status is 1 yes should be chosen dynamically. Can anybody help me how to do this using angular js

You can use ng-checked , see example below:

<div ng-repeat="data in tdata">
        <div>
        {{data.name}} : yes:<input type="radio" name={{data.name}} ng-checked="data.status === 1"/> &nbsp No:<input type="radio" name={{data.name}} ng-checked="data.status === 0"/> <br/>
        </div>
    </div>

Try that, i'm not on my PC

<div ng-repeat="data in tdata">
    <div>
    {{data.name}} : yes:<input type="radio" {{(data.status == 1 ? "checked='checked'" : '')}} name={{data.name}}/> &nbsp No:<input type="radio" {{(data.status == 0 ? "checked='checked'" : '')}}name={{data.name}}/> <br/>
    </div>
</div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM