Angularjs Checkbox Dynamic Ng-true-value Expression
Solution 1:
It seems ng-true-value
does not accept non-constant expressions. From the docs(v1.3.0):
Some attributes used in conjunction with ngModel (such as ngTrueValue or ngFalseValue) will only accept constant expressions.
Examples using constant expressions include:
<inputtype="checkbox" ng-model="..." ng-true-value="'truthyValue'">
<inputtype="checkbox" ng-model="..." ng-false-value="0">
Examples of non-constant expressions include:
<inputtype="checkbox" ng-model="..." ng-true-value="someValue">
<inputtype="checkbox" ng-model="..." ng-false-value="{foo: someScopeValue}">
An ideal workaround probably would be calling a Controller method on ng-click
or ng-change
inside which you can analyse all the checkboxes for truthy or non-truthy values.
Solution 2:
Another approach is to delay the creation of the checkbox until the value is ready (on scope or whatever).
In my case I was loading a value via http that wasn't on the scope when the checkbox was created. So I just wrapped it in an ng-if.
<divclass="checkbox"ng-if="viewData.conditionId != undefined"><label><inputtype="checkbox"ng-true-value="{{'\''+ viewData.conditionId + '\''}}"ng-false-value="undefined"ng-model="model.conditionId"required />
I agree
</label></div>
Which worked perfectly for my scenario. Yours is a bit different but the same principal should apply - delay creation of the checkbox until you know the value being bound is there.
And yes the stupid quotation marks seem to be necessary.
Solution 3:
Expression in the ng-true-value will be evaluated only once, so it won't be dynamic.
One alternative approach is to calculate the values in ng-change callback instead.
Please see my fork http://plnkr.co/edit/9zYS3OZ0sSkXX9rHwcgv?p=preview for the full example.
In html:
<inputtype="checkbox" ng-model="selectedDays.monday" ng-change="calculatePrice()" /> Mon
<inputtype="checkbox" ng-model="selectedDays.tuesday" ng-change="calculatePrice()" /> Tue <br />
<inputtype="checkbox" ng-model="selectedDays.wednesday" ng-change="calculatePrice()" /> Wed
<inputtype="checkbox" ng-model="selectedDays.thursday" ng-change="calculatePrice()" /> Thu <br />
<inputtype="checkbox" ng-model="selectedDays.friday" ng-change="calculatePrice()" /> Fri
and in controller:
$scope.calculatePrice = function(){
$scope.formData.location.day = {};
angular.forEach($scope.selectedDays, function (selected, day) {
if (selected) {
$scope.formData.location.day[day.slice(0, 3)] = $scope.data.bso[$scope.formData.location.ID].prices[day];
}
});
}
$scope.selectedDays = {};
Post a Comment for "Angularjs Checkbox Dynamic Ng-true-value Expression"