我正在尝试查看用户是否已经订阅了计划,如果已经订阅,请检查相应的单选按钮。
我有一组md单选按钮,我正在用ng repeat:创建
<md-radio-group class="md-primary" ng-model="plan">
<div flex ng-repeat="planInfo in plans" class="plan-options">
<md-radio-button value="{{planInfo._id}}" name="plan" class="md-primary" ng-checked="hasPlanID == planInfo._id" required>
<h2 class="plan-name">{{planInfo.name}}</h2>
<h3 class="plan-price">${{planInfo.price}}</h3>
</md-radio-button>
</div>
</md-radio-group>
我有一个从数据库中获取所有计划的服务:
//check to see if user already has a plan
MyService.GetPlan(currentUser.username).then(function (response) {
if (response.success) {
//This does resolve correctly
$scope.hasPlanID = response.data.plan;
MyService.GetAllPlans().then(function (response) {
if (response.success) {
//plans display properly
$scope.plans = response.data;
} else {
$log.debug(response.message);
}
});
} else {
$log.debug(response.message);
}
});
请注意HTML中的ng-checked属性。当我查看Chrome的检查器时,它会准确地显示出你在代码中看到的内容,ng-checked="hasPlanID==planInfo_id"。
如何让它识别变量值并将实际表达式解析为true或false?
明白了。看起来ng-checked不适用于md单选按钮,它只适用于html输入。您必须使用ng class指令将md选中的类添加到md单选按钮元素中,该指令可以计算表达式:
<md-radio-button value="{{planInfo._id}}" name="plan" class="md-primary" ng-class="{'md-checked':$parent.hasPlanID == planInfo._id}" required>
您不应该手动处理该检查。不填充$scope.hasPlanID
属性,只需将$scope.plan
设置为当前计划,如下所示:
//check to see if user already has a plan
MyService.GetPlan(currentUser.username).then(function (response) {
if (response.success) {
//This does resolve correctly
$scope.plan = response.data.plan;
MyService.GetAllPlans().then(function (response) {
if (response.success) {
//plans display properly
$scope.plans = response.data;
} else {
$log.debug(response.message);
}
});
} else {
$log.debug(response.message);
}
});
这应该会自动处理检查,因为您的模型设置为$scope.plan
:
<md-radio-group class="md-primary" ng-model="plan">
$scope.sel = 'lu';
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<md-radio-group ng-model="sel" ng-change="logos()" ng-model="myValue" class="settings-radio-button" layout="row">
<md-radio-button value="lu" ng-checked="true" class="md-primary">Upload With URL</md-radio-button>
<md-radio-button value="li" class="md-primary">Select Logo Image</md-radio-button>
</md-radio-group>
如果您想将单选按钮检查为 md-radio-button
,请使用 ng-value
而不是不带 ng-checked
的 value
,例如
<md-radio-group class="md-primary" ng-model="plan">
<div flex ng-repeat="planInfo in plans" class="plan-options">
<md-radio-button ng-value="planInfo._id" name="plan" class="md-primary" ng-checked="hasPlanID == planInfo._id" required>
<h2 class="plan-name">{{planInfo.name}}</h2>
<h3 class="plan-price">${{planInfo.price}}</h3>
</md-radio-button>
</div>
</md-radio-group>
此代码段将对计划的值进行建模,并根据planInfo的值选择适当的单选按钮_id。
希望这会有所帮助!