2017-03-16 44 views
1

我正在基於ng-repeat創建div。我從數據庫中獲取數據。數據如下:複合角腳本

[ 
    { 
     id:1, 
     name:item1, 
     category: [catA, catB, catC,] 
    }, 
    { 
     id:2, 
     name:item2, 
     category: [catB] 
    }, 
    { 
     id:3, 
     name:item3, 
     category: [catA, catB] 
    } 
] 

該數據在一個範圍內。所以:

myApp.controller("myCtrl", function($scope, $http){ 

    var cat = "catA"; 

    $http.get("/getdata", function(response){ 
     if(response.data){ 
      $scope.items = response.data; 

      if(response.data.category==cat){ // Check if the var cat is present in the array. How to do this? 
       //set ng-class for the button in the div to 'active'. How to do this? 
      } 

     } else { 
      $scope.message = "Nothing returned."; 
     } 
    }); 

    $scope.send = function(n){ 
     $scope.isActive = !$scope.isActive; 
    } 
}); 

我使用NG-重複:

<div ng-repeat="item in items" class="myclass"> 
     {{item.name}} 
     <button class="myRight" ng-class="{'active': isActive}" ng-click="send(item.id)"> click </button> 
</div> 

活動類:

.active { background: #FF735C; color:white;} 

因此,基於該var cat目前category在接收到的數據在陣列中,按鈕的類別決定。如果點擊該按鈕,該類將切換。我無法使用$ index作爲按鈕來傳遞var,就好像數據被過濾一樣,正確的索引也不會被渲染。

我有權使用ng級嗎?有沒有其他更簡單的方法來實現這一目標?

請幫忙。非常感謝。

+0

所以確認,按鈕應該是'active'如果該項目有'catA'作爲一個類別,而不是'active'一旦按下按鈕? – Ankh

+0

是的。究竟。如果一個項目沒有像'item2'這樣的'catA',那麼這個div中的按鈕應該沒有活動類。 – Somename

+0

如果點擊了一個活動按鈕,它會變成「不活動」並且無法再次點擊? – Ankh

回答

1

希望這應該能解決您的問題,ng-class絕對是正確的選擇。

// our store of active buttons/items 
$scope.buttonActive = {}; 

$http.get("/getdata", function(response) 
{ 
    if (response.data) 
    { 
     angular.forEach(response.data, function (item) 
     { 
      // create a list of active items based on if it has a category 
      $scope.buttonActive[item.id] = item.category.indexOf(cat) !== -1; 
     }); 

     $scope.items = response.data; 
    } 
    else 
    { 
     $scope.message = "Nothing returned."; 
    } 
}); 

/** 
* @param id 
*/ 
$scope.send = function (id) 
{ 
    // toggle the boolean value for this button/item's state 
    $scope.buttonActive[id] = !$scope.buttonActive[id]; 
} 

而且在模板:

<div ng-repeat="item in items" class="myclass"> 
    {{ item.name }} 
    <button class="myRight" ng-class="{ 'active': buttonActive[item.id] }" ng-click="send(item.id)">click</button> 
</div> 

UPDATE

if報表基本上是通過評估一個或多個條件爲布爾值工作。

if (true) 
    doSomething(); 

所以我在做什麼在該行是這樣的:

// if item.categories array contains the category in 'cat' variable 
if (item.category.indexOf(cat) !== -1) 
    $scope.buttonActive[item.id] = true; 
else 
    $scope.buttonActive[item.id] = false; 

但看到我指定取決於另一個布爾值布爾值,我可能也只是使用的結果的初始條件。

var isInArray = item.category.indexOf(cat) !== -1; 

$scope.buttonActive[item.id] = isInArray; 

或者只是:

$scope.buttonActive[item.id] = item.category.indexOf(cat) !== -1; 
+0

這個魔法叫什麼? '$ scope.buttonActive [item.id] = item.category.indexOf(cat)!== -1' 我可以在哪裏瞭解更多信息? – Somename