2016-07-02 130 views
0

所以我有兩個按鈕,它們的作用是當單擊其中一個按鈕時顯示它們各自的數據。現在第一次加載頁面時顯示活動顏色 - AngularJS

<div> 
    <h1>Ng-show & ng-hide</h1> 
    <p class="description">Click on the "show"-link to see the content.</p> 
    <button ng-click="showme=true" ng-class="{activeButton: showme == true}">Show</button> 
    <button ng-click="showme=false" ng-class="{activeButton: showme == false}">Hide</button> 

    <div class="wrapper"> 
    <p ng-hide="showme">It will appear here!</p> 
    <h2 ng-show="showme">This is mah content, yo!</h2> 
    </div> 
</div> 

,我加入了NG-類顯示一個積極的顏色(說「紅」),當按鈕被點擊,另一個應該回到它的原始顏色(藍色)。當頁面加載時,我看到的第一件事是「它會出現在這裏!」的消息。這很好,但代表(「隱藏」)此消息的按鈕不具有活動的紅色。

當頁面首次加載到此按鈕時,我如何設置默認的活動顏色?我想保持切換功能,我應該可以點擊一個按鈕,看到活動的顏色。

您的幫助將不勝感激,提前致謝!

+0

設置的showme值作爲true'NG-init'或定義'showme'在控制器... – Rayon

+0

頁面加載後的第一次,變量'showme'沒有任何值,所以它等於'undefined'。通過上面的代碼,將'ng-class'的值改爲'{activeButton:showme}'和'{activeButton:!showme}'會起作用 –

+0

謝謝你們,這真的有幫助! AngularJS的全新 – medev21

回答

1

NullUndefined類型是嚴格相等(==)給自己和抽象地等於(==)到彼此。[Ref]

在你ng-class語句,既不條件得到滿足,因此class不適用。在ng-show/hide中,undefined被評估爲false因此「它會出現在這裏!」正在顯示

在控制器

var myApp = angular.module('myApp', []); 
 
myApp.controller('myCtrl', function($scope) { 
 
    $scope.showme = false; 
 
})
.activeButton { 
 
    color: green; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> 
 
<div ng-app="myApp" ng-controller="myCtrl"> 
 
    <h1>Ng-show & ng-hide</h1> 
 
    <p class="description">Click on the "show"-link to see the content.</p> 
 
    <button ng-click="showme=true" ng-class="{activeButton: showme}">Show</button> 
 
    <button ng-click="showme=false" ng-class="{activeButton: !showme}">Hide</button> 
 

 
    <div class="wrapper"> 
 
    <p ng-hide="showme">It will appear here!</p> 
 
    <h2 ng-show="showme">This is mah content, yo!</h2> 
 
    </div> 
 
</div>

+0

簡單地評估'showme'在視圖中作爲布爾值而不使用== == – charlietfl

+0

@charlietfl - 編輯是否正確?你的意思是一樣的嗎? – Rayon

+0

是的...少寫和做同樣的事 – charlietfl

相關問題