2016-05-13 6 views
0

特定のクラス名を持つ要素を数えようとしていますが、これはトグルコントロールの一部として追加および削除されます。これは、報告されたカウントが正しくないことを意味します。クラス名による要素が期待通りに動作しない

現在の実装で最初に選択された要素がスキップされて(つまりカウントされない)、2番目の要素でカウントされることに気付きました。次のように

私のコードは次のとおりです。

ビュー

<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

あなたのコードのdoesntの仕事。あなたが書いたことを確認してください:をクリックしてください。また、クラスを数えるこのことは良い考えではありません。選択した項目を配列にプッシュして、代わりに配列の長さを数えてみませんか? – yBrodsky

+0

http://jsfiddle.net/rvukp5Lh/基本的には動作しています。 –

+0

選択した項目を配列にプッシュするにはどうすればよいですか? – methuselah

答えて

1

ちょうど=== true=== falseを取り除く。

代わりに実行します。あなたのスペルミスのNG-クリック原因

ng-class="{ 
    'button-custom-padding': bookingSelected, 
    'button-positive': !bookingSelected, 
    'booking-selected' : bookingSelected, 
    'button-balanced': bookingSelected 
}" 
関連する問題