ng-repeat with ng-click function if else Angular

ng-repeat with ng-click function if else Angular

当您单击其中一个插件时,在 ng-class="{{sectionClass}}" 中,我想向该元素添加一个 class。

有没有更好的方法来完成这个?

我的方法不行,我不确定代码有什么问题。

            $scope.addOns = [
              
             {                        
                    name: "Cover options"
                },
                {
                    name: "Stamping"
                }
            ];

            $scope.sectionClass = function(addOn){

             if (addOn.name == "Cover options")

              return("covers");

             else if (addOn.name == "Stamping")

              return("stamping");

            }
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div class="section-content" ng-class="{{sectionClass}}"> 
    <div class="add-on-type" ng-click="sectionClass(addOns)" ng-repeat="addOn in addOns">
        <span>{{addOn.name}}</span>
    </div>
</div>

你错过了一些东西

  1. ng-repeatng-click函数传递addon对象,类似于ng-click="sectionClass(addOn)"

  2. 不要 return 方法中的字符串而是设置一个范围变量,如 customClass 并在 ng-class 指令中使用它

HTML

<div ng-app="myApp" ng-controller="MyCtrl" >
    <div class="section-content" ng-class="{{customClass}}">
        <div class="add-on-type" ng-click="sectionClass(addOn)" ng-repeat="addOn in addOns"> <span>{{addOn.name}}</span>
        </div>
    </div>
</div>

控制器

var myApp = angular.module('myApp', []);

myApp.controller('MyCtrl', function ($scope) {
    $scope.addOns = [

    {
        name: "Cover options"
    }, {
        name: "Stamping"
    }];

    $scope.sectionClass = function (addOn) {
        if (addOn.name == "Cover options")
            $scope.customClass="covers"

        else if (addOn.name == "Stamping")
            $scope.customClass="stamping"    
    }
});

Working Fiddle

希望对您有所帮助。谢谢。