簡體   English   中英

使用AngularJS的條件CSS

[英]Conditional css using angularjs

我是新手,在單擊時嘗試更改樣式。 我有一個模板,並使用頁面上的相同模板創建了2-3個內容空間。 當用戶單擊“更多”鏈接時,我要擴展該部分。 我能夠使用下面的代碼來觸發CSS

<a href="#" ng-click="isActive = !isActive"><strong>more</strong></a>

我苦苦掙扎的地方是,如果用戶單擊另一個部分以展開,我想折疊之前展開的部分並展開當前部分,而當前的展開適用於當前部分。

如果要折疊其他布爾真/假變量,則不僅需要布爾真/假變量。 這是一種方法。

<a ng-click="active = 0" ng-class="{show: active==0}"></a>
<a ng-click="active = 1" ng-class="{show: active==1}"></a>

如果您願意,也可以將其與ng-repeat結合使用

<a ng-repeat="section in sections" ng-click="active = $index" ng-class="{show: active==$index}"></a>

如果您只想在任何給定時間選擇一項,請通過$ scope上的selectedItem進行驅動,然后在模板中使用ng-if檢查所選項是否為當前項。 例:

 angular.module('myApp', []) .controller('MainController', function ($scope) { var items = [], vm = {}; // properties $scope.vm = vm; vm.items = items; vm.selectedItem = null; //methods vm.setItem = function (item) { // reset current item to more if (vm.selectedItem) { vm.selectedItem.detailsText = 'More'; } // collapse if selecting same item if (item === vm.selectedItem) { vm.selectedItem = null; return; } item.detailsText = 'Less'; vm.selectedItem = item; }; activate(); // initialization logic function activate() { for(var i = 0; i < 15; ++i) { items.push({id: i, title: 'Item: ' + i, details: 'Item ' + i + ' Details', detailsText: 'More'}); } } }); 
 html { box-sizing: border-box; } *, *:before, *:after { box-sizing: inherit; } a { color: #004b8d; text-decoration: underline; cursor: pointer; } a:hover { color: #2c88e6; text-decoration: none; } .container { width: 500px; border: 1px solid black; } .item { padding: 12px; border-bottom: 1px solid gray; } .item:last-child { border: 0; } .details { margin-left: 10px; color: green; } 
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <div ng-app="myApp" ng-controller="MainController" class="container"> <div class="item" ng-repeat="item in vm.items"> {{item.title}} <a ng-click="vm.setItem(item)">{{item.detailsText}}</a> <div class="details" ng-if="vm.selectedItem === item"> {{item.details}} </div> </div> </div> 

這將使通過控制器和模板進行更新變得更加容易,而不是例如必須復制模板的某些部分以使其停用。 任何邏輯也直接存在於控制器內部,這對於單元測試而言更好。 例如:

it('should update selected item', function () {
    // ... initialize controller and $scope properties
    var item = {};
    $scope.vm.setItem(item);
    expect($scope.vm.selectedItem).toBe(item);
    expect(item.detailsText).toBe('Less');
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM