babtech
babtech

Reputation: 159

Checking whether the radio button is disabled or not

I have a radio button. I need to add a value to the scope based on the radio button is disabled or enabled.

<div ng-app="app">
<div ng-controller="Ctrl" class="cont">
    <input type="checkbox" ng-model="checked" />
    <input type="radio" ng-disabled='!checked' />
    <p>{{value}}</p>
</div>    
</div>


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

function Ctrl($scope) {
   if($scope.checked){
   $scope.value = "test";
  }   
}

fiddle

Upvotes: 0

Views: 4398

Answers (2)

DarkLeafyGreen
DarkLeafyGreen

Reputation: 70406

Even more simple:

<div ng-app="app">
    <div ng-controller="Ctrl" class="cont">
        <input type="checkbox" ng-model="checked" />
        <input type="radio" ng-disabled='!checked' />
        <!-- Test or {{ value }} -->
        <p ng-show="checked">Test</p>
    </div>    
</div>

However if you want to monitor the state of checked in your js code you have to use $watch like Satpal said in his answer. Or you use ng-change:

<input type="checkbox" ng-change="change()" ng-model="checked" />
<p ng-show="checked">{{ $scope.test }}</p>

$scope.change = function() {
    if($scope.checked)
        $scope.test = "Test";
    else
        $scope.test = "";
};

See here: http://docs.angularjs.org/api/ng.directive:ngChange

Upvotes: 1

Satpal
Satpal

Reputation: 133403

You can use $watch, it registers a listener callback to be executed whenever the watchExpression changes.

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

function Ctrl($scope) {
    //Set Initial Value
    $scope.value = '';
    //Listen to value change of $scope.checked
    $scope.$watch(function () {
        return $scope.checked;
    }, function (new_value) {
        if ($scope.checked) {
            $scope.value = "test";
        } else {
            $scope.value = "";
        }
    });
}

Working Demo

Upvotes: 0

Related Questions