按类名计算元素不按预期工作

时间:2016-05-13 14:54:46

标签: javascript angularjs

我正在尝试计算具有特定类名的元素,这些元素作为切换控件的一部分添加和删除。这意味着报告的计数不正确。

我注意到我当前的实现跳过了第一个选中的元素(即不计数),只开始计算第二个元素。

我的代码如下:

查看

<div ng-controller="MyCtrl">
  <div class="item item-button-right" ng-repeat="i in [1, 2, 3, 4]">

    Full Colour
    <p>&pound;50 and up to 1 hour</p>

    <button class="button button-custom" ng:click="bookingSelected = !bookingSelected; 
                              $parent.$parent.activeProfileHeader = false;
                              $parent.$parent.displayBookingFooter(true);" ng-class="{ 'button-custom-padding': bookingSelected === true, 
                                'button-positive': bookingSelected === false,
                                'booking-selected' : bookingSelected === true, 
                                'button-balanced': bookingSelected === true}">{{bookingSelected && '✔' || 'Book'}}</button>
  </div>

<br>

  Total: {{numItems('booking-selected')}}

</div>

控制器

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

//myApp.directive('myDirective', function() {});
//myApp.factory('myService', function() {});

function MyCtrl($scope, $window) {
  $scope.bookingSelected = false;

  $scope.numItems = function(className) {
    return $window.document.getElementsByClassName(className).length;
  };
}

小提琴:http://jsfiddle.net/ha5oac6v/

更新:抱歉显示,jsfiddle中的代码不起作用。

1 个答案:

答案 0 :(得分:1)

摆脱=== true=== false

取而代之的是:

ng-class="{ 
    'button-custom-padding': bookingSelected, 
    'button-positive': !bookingSelected,
    'booking-selected' : bookingSelected, 
    'button-balanced': bookingSelected
}"