2016-09-18 47 views
0

$范围我有四个值与名称:角 - 字符串连接到环

$scope.restaurant.restaurantIsTop 
$scope.restaurant.restaurantIsRecommended 
$scope.restaurant.restaurantIsNew 
$scope.restaurant.restaurantIsPromoted 

他们每个人都可以是0或1。我想检查它们的值是否等于1,将其更改为true,否则将为false。

我可以用这个方法四个变量做到这一点:

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

当然它的工作原理,但它并不适用于多个值有效的方式。所以我创建了一个数组:

var varietyArray = ["restaurantIsTop" , 
           "restaurantIsRecommended", 
           "restaurantIsNew", 
           "restaurantIsPromoted" 

      ]; 

     angular.forEach (varietyArray, function (val) { 

      console.log($scope.restaurant.val); 
     }) 

我想在上面的循环中检查四个变量。任何建议?

编辑:

我想向他们展示在角材质复选框:

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

'0'和'1'默认为'falsy'和'truthy'。如果你对同一个变量进行修改,它会改变它的含义。你想在视图上显示真或假?或者它只是用于内部计算? –

+0

如果它只有4个这样的值,If Else是完美的。如果可能,请避免使用三元运算符。以下是链接。 http://stackoverflow.com/a/12022491/1907391 –

+0

此外0是错误的,最终是真实的。 –

回答

1

要检查您的循环中的变量,并有条件地设置它,你可以把它这种方式:

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]); 
}) 

您可以通过以下方式访问示波器变量:$scope[VariablenameAsString]

jsfiddle

0

正如有人已经评论,你并不需要更改这些属性的值。 0相当于假,1相当于真。

材料复选框应至少在通过复选框呈现数据解释这些值作为“falsy”或“truthy”所以我认为你应该罚款。

但是请记住,当他们改变复选框会“写”模型(属性)正确的布尔值,你可以混合0,1,真,假值结束。

希望这会有所帮助!