AngularJs:我想从数组或列表中添加一个类,用于ng-repeat中的每次迭代

AngularJs: I want to add a class from an array or list, for each iteration inside ng-repeat

本文关键字:一个 用于 ng-repeat 迭代 数组 添加 列表 AngularJs      更新时间:2023-09-26

如果我在作用域中有下一个数组

$scope.colors = [
    "red",
    "blue",
    "yellow",
    "orange",
    "black",
    "purple"
];

我使用 ng 重复

<div ng-repeat="car in cars">

我希望在该div 上的每次迭代都将添加 $scope.colors 中的一种颜色。我想随机或按顺序添加它。

我发现该链接 http://www.whatibroke.com/?p=938 有一个指令可以从列表中添加一个随机类,但我无法让它在 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等的东西,但更喜欢使用更具描述性的类名。

谢谢

只要

正确绑定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>

普罗提

相关文章: