如果是Angular,则使用ng-click函数进行ng-repeat

时间:2015-02-18 19:53:36

标签: javascript angularjs class angularjs-ng-repeat angularjs-ng-click

当您点击其中一个addOn时,在ng-class =" {{sectionClass}}"中,我想为该元素添加一个类。

有没有更好的方法来实现这一目标?

我的方式不起作用,我不确定代码有什么问题。



            $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>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)

你错过了几件事

  1. addon ng-repeat函数传递ng-click个对象,如ng-click="sectionClass(addOn)"

  2. 不要从方法返回字符串,而是设置一个范围变量,如customClass&amp;在ng-class指令

  3. 中使用它

    <强> 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

    希望这可以帮到你。感谢。