检查单选按钮是否被禁用

时间:2013-12-26 09:07:02

标签: angularjs radio-button

我有一个单选按钮。我需要根据禁用或启用的单选按钮向范围添加值。

<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

2 个答案:

答案 0 :(得分:1)

更简单:

<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>

但是,如果你想监视你的js代码中的已检查状态,你必须使用像Satpal一样的手表。或者你使用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 = "";
};

见这里:http://docs.angularjs.org/api/ng.directive:ngChange

答案 1 :(得分:0)

您可以使用$watch,它会在watchExpression发生更改时注册要执行的侦听器回调。

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