Angularjs 复角体
我正在基于ng repeat创建div。我正在从数据库获取数据。数据如下:Angularjs 复角体,angularjs,angularjs-ng-repeat,Angularjs,Angularjs Ng Repeat,我正在基于ng repeat创建div。我正在从数据库获取数据。数据如下: [ { id:1, name:item1, category: [catA, catB, catC,] }, { id:2, name:item2, category: [catB] }, { id:3, name:item3, categ
[
{
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>
因此,根据数据中收到的category
数组中的var cat
,确定按钮的类别。如果单击该按钮,该类将切换。我不能使用$index作为按钮来传递var,就好像数据被过滤了一样,正确的索引没有被呈现
我使用ng类正确吗?有没有其他更简单的方法来实现这一点
请帮忙。非常感谢。希望这能解决您的问题,
ng类绝对是正确的选择
// 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>
所以我在这条线上做的是:
// 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;
因此,要确认,如果项目将catA
作为一个类别,则按钮应处于活动状态
,而按下按钮后按钮不处于活动状态?是。确切地如果项目没有像item2
那样的catA
,则此div中的按钮不应具有活动类。如果单击了活动按钮,则该按钮是否会变为“非活动”且无法再次单击?谢谢。不,只是上课而已。该按钮可再次单击。只有类可以切换。我在问题中加入了这个类。这个魔法叫什么<代码>$scope.buttonActivity[item.id]=item.category.indexOf(cat)!=-1
在哪里可以了解更多信息?
var isInArray = item.category.indexOf(cat) !== -1;
$scope.buttonActive[item.id] = isInArray;
$scope.buttonActive[item.id] = item.category.indexOf(cat) !== -1;