Reputation: 2493
I have four values with names :
$scope.restaurant.restaurantIsTop
$scope.restaurant.restaurantIsRecommended
$scope.restaurant.restaurantIsNew
$scope.restaurant.restaurantIsPromoted
Each of them can be 0 or 1 . I want to check them if their value is equal to 1 , change it to true , otherwise it would be false.
I could do this with this method for four variable:
if ($scope.restaurant.restaurantIsTop == 1 ?
$scope.restaurant.restaurantIsTop = true :
$scope.restaurant.restaurantIsTop = false);
if ($scope.restaurant.restaurantIsNew == 1 ?
$scope.restaurant.restaurantIsNew = true :
$scope.restaurant.restaurantIsNew =false);
if ($scope.restaurant.restaurantIsRecommended == 1 ?
$scope.restaurant.restaurantIsRecommended = true :
$scope.restaurant.restaurantIsRecommended =false);
if ($scope.restaurant.restaurantIsPromoted == 1 ?
$scope.restaurant.restaurantIsPromoted = true :
$scope.restaurant.restaurantIsPromoted =false);
Absolutely it works but It's not efficient way for multiple value. So I created an array :
var varietyArray = ["restaurantIsTop" ,
"restaurantIsRecommended",
"restaurantIsNew",
"restaurantIsPromoted"
];
angular.forEach (varietyArray, function (val) {
console.log($scope.restaurant.val);
})
And I want to check four variable in above loop . Any suggestion ?
EDITED :
I want to show them in Angular Material checkbox :
<div class="col-sm-12">
<div class="md-form-group">
<md-checkbox ng-model="restaurant.restaurantIsTop ">
best
</md-checkbox>
<md-checkbox ng-model="restaurant.restaurantIsRecommended">
suggested
</md-checkbox>
<md-checkbox ng-model="restaurant.restaurantIsNew">
new
</md-checkbox>
<md-checkbox ng-model="restaurant.restaurantIsPromoted">
promote
</md-checkbox>
</div>
</div>
Upvotes: 0
Views: 381
Reputation: 873
As someone already commented you don't need to change the value of those properties. 0 is equivalent to false and 1 is equivalent to true.
The Material checkbox should interpret those values as "falsy" or "truthy" so I think you should be fine at least in presenting the data through the checkboxes.
Nonetheless keep in mind that the checkboxes would "write" proper bool values in the model (property) when they change and you could end up with mixed 0, 1, true, false values.
Hope this helps!
Upvotes: 0
Reputation: 911
To check the variable within your loop and set it conditionally you can to it this way:
var $scope = {
restaurantIsTop: 1,
restaurantIsRecommended: 0,
restaurantIsNew: 0,
restaurantIsPromoted: 1
};
var varietyArray = ["restaurantIsTop" ,
"restaurantIsRecommended",
"restaurantIsNew",
"restaurantIsPromoted"
];
angular.forEach (varietyArray, function (val) {
$scope[val] = ($scope[val]) ? false : true;
console.debug($scope[val]);
})
You can access the scope variable with $scope[VariablenameAsString]
Upvotes: 1