2016-04-11 8 views
0

私は項目のリストを持っており、リスト内の各項目のオプションとして有効/無効のメソッドを持っています。ng-repeatで選択した項目のAngledJsトグル機能

私は、リストに項目を1つだけ切り替えたい: enter image description here

現在の実装では、リスト内のすべての項目を切り替え、そしてすべてのクラスのアイコンを変更します。

HTML

<div class="device" ng-repeat="item in items" ng-class="{'open': item.isOpen}"> 
    <!-- Enable/Disable--> 
    <a href="#" class="m-r-20" ng-click="test.toggleMethod(item.Id)"> 
    <span class="{{test.buttonClassIcon}}" title="{{test.title}}"></span> 
    </a> 
</div> 

コントローラ

model.enabled = true; 
model.toggleMethod = function (deviceId) { 

    if (model.enabled) { 
     locationService.start(deviceId).then(deviceList); 
    } else { 
     locationService.stop(deviceId).then(deviceList); 
    } 

    model.enabled = !model.enabled; 
    model.buttonClassIcon = model.enabled ? 'fa fa-bell' : 'fa fa-bell-slash'; 
    model.title = model.enabled ? 'Enable' : 'Disable'; 

}; 

私はベルをクリックすると、それはすべてのクラスを変更し、グローバル変数を切り替えます。

+0

あなたのコントローラに 'toggleMethod()'の定義はありませんか?それは 'toggleAlarmMethod()'ですか? – dreamweiver

+0

さらに、オープンは何をしていますか?コントローラーでも定義されていません。 –

答えて

2

リストの各要素にはenabledプロパティが必要です。

<a href="#" class="m-r-20" ng-click="test.toggleMethod(item)"> 
    <span ng-if="item.enabled" class="fa fa-bell" title="Enable"></span> 
    <span ng-if="!item.enabled" class="fa fa-bell-slash" title="Disable"></span> 
</a> 

か、ng-classを使用するか、対応するタイトルを返しgetTitle(item.enabled)のような関数を作成することができます。HTMLで

model.items.map(function(item){ 
    item.enabled = false; // or other default value 
}); 

と。

toggleMethod

model.toggleMethod = function (device) { 
    var deviceId = device.Id; 
    if (device.enabled) { 
     locationService.start(deviceId).then(deviceList); 
    } else { 
     locationService.stop(deviceId).then(deviceList); 
    } 

    device.enabled = !device.enabled; 
}; 

ここではfiddleです。

これはあなたが達成しようとしていたものです。

0

選択した項目を有効/無効にするのではなく、モデルオブジェクトを有効/無効にします。 私はあなたのスニペットに従って、前提を作るつもりです。

あなたはアイテムIDを持っているか、あなたが行うことができます$インデックス(項目の配列に位置)を渡すことができますので:

:選択した項目をチェックし

//also pass $index into ng-click function 
     <a href="#" class="m-r-20" ng-click="test.toggleMethod(item.Id,$index)"> <span class="{{test.buttonClassIcon}}" title="{{test.title}}"></span> </a> 

と関数本体内を

model.toggleAlarmMethod = function (deviceId,indx) { if ($scope.items[indx].enabled) { locationService.start(deviceId).then(deviceList); } else { locationService.stop(deviceId).then(deviceList); } //enable/disable selected item $scope.items[indx].enabled = !$scope.items[indx].enabled; $scope.items[indx].buttonClassIcon = $scope.items[indx].enabled ? 'fa fa-bell' : 'fa fa-bell-slash'; $scope.items[indx].title = $scope.items[indx].enabled ? 'Enable' : 'Disable'; }; 
関連する問題