AngularJs:我想从数组或列表中为 ng-repeat 中的每次迭代添加一个 class
AngularJs: I want to add a class from an array or list, for each iteration inside ng-repeat
如果范围内有下一个数组
$scope.colors = [
"red",
"blue",
"yellow",
"orange",
"black",
"purple"
];
我使用 ng-repeat
<div ng-repeat="car in cars">
我希望在 div 的每次迭代中添加 $scope.colors 中的一种颜色。
我想随机添加或按顺序添加。
我发现 link http://www.whatibroke.com/?p=938 那里有一个从列表中随机添加 class 的指令,但我无法让它在 ng-repeat 中工作,我粘贴了该示例中的代码以防万一。
app.directive("ngRandomClass", function () {
return {
restrict: 'EA',
replace: false,
scope: {
ngClasses: "="
},
link: function (scope, elem, attr) {
//Add random background class to selected element
elem.addClass(scope.ngClasses[Math.floor(Math.random() * (scope.ngClasses.length))]);
}
}
});
<div class="test" ng-random-class ng-classes="classes"></div>
我知道我可以使用 $index 创建类似 myclass1、myclass2、myclass3 等的内容,但我更愿意使用更具描述性的 class是名字。
谢谢
只要正确绑定 two-way
绑定 属性,就可以让它工作。您也可以将指令属性名称本身重新用于双向绑定属性,以避免再添加一个属性。
尝试:
.directive("ngRandomClass", function () {
return {
restrict: 'EA',
replace: false,
scope: {
ngClasses: "=ngRandomClass"
},
link: function (scope, elem, attr) {
//Add random background class to selected element
elem.addClass(scope.ngClasses[Math.floor(Math.random() * (scope.ngClasses.length))]);
}
}});
并将其用作:
<div ng-repeat="car in cars">
<div class="test" ng-random-class="colors">{{car}}</div>
</div>
如果范围内有下一个数组
$scope.colors = [
"red",
"blue",
"yellow",
"orange",
"black",
"purple"
];
我使用 ng-repeat
<div ng-repeat="car in cars">
我希望在 div 的每次迭代中添加 $scope.colors 中的一种颜色。 我想随机添加或按顺序添加。
我发现 link http://www.whatibroke.com/?p=938 那里有一个从列表中随机添加 class 的指令,但我无法让它在 ng-repeat 中工作,我粘贴了该示例中的代码以防万一。
app.directive("ngRandomClass", function () {
return {
restrict: 'EA',
replace: false,
scope: {
ngClasses: "="
},
link: function (scope, elem, attr) {
//Add random background class to selected element
elem.addClass(scope.ngClasses[Math.floor(Math.random() * (scope.ngClasses.length))]);
}
}
});
<div class="test" ng-random-class ng-classes="classes"></div>
我知道我可以使用 $index 创建类似 myclass1、myclass2、myclass3 等的内容,但我更愿意使用更具描述性的 class是名字。
谢谢
只要正确绑定 two-way
绑定 属性,就可以让它工作。您也可以将指令属性名称本身重新用于双向绑定属性,以避免再添加一个属性。
尝试:
.directive("ngRandomClass", function () {
return {
restrict: 'EA',
replace: false,
scope: {
ngClasses: "=ngRandomClass"
},
link: function (scope, elem, attr) {
//Add random background class to selected element
elem.addClass(scope.ngClasses[Math.floor(Math.random() * (scope.ngClasses.length))]);
}
}});
并将其用作:
<div ng-repeat="car in cars">
<div class="test" ng-random-class="colors">{{car}}</div>
</div>