angular學習筆記(九)-css類和樣式2

來源:互聯網
上載者:User

標籤:style   blog   class   code   java   ext   

在上一個例子中,元素的類名使用拼接的方法,這樣,類名中就不得不帶有true或false,並且不易維護,所以,angular使用ng-class屬性來控制元素的類名:

我們來看一個小例子,點擊error按鈕,頂部提示錯誤框,點擊warning按鈕,頂部提示警告框.

錯誤框的類名是.err,警告框的類名是.warn:

<!DOCTYPE html><html ng-app><head>  <title>6.2css類和樣式</title>  <meta charset="utf-8">  <script src="../angular.js"></script>  <script src="script.js"></script>  <style type="text/css">    *{      font-family:‘MICROSOFT YAHEI‘;      font-size:12px    }    .tip {      margin:auto; width:300px; height:30px; line-height:30px; text-align:center;    }    .err {      color:#A91818; background:#F3976C    }    .warn {      color:#F3976C; background:#F6EBBC;    }    button {      border:1px solid #ccc; outline:0    }  </style></head><body><div ng-controller = "WarnErr">  <div>    <div class="tip" ng-class="{err:ifErr,warn:ifWarn}" ng-show="ifShow">{{tipText}}</div>  </div>  <div>    <button ng-click="showErr()">error</button>    <button ng-click="showWarn()">warning</button>  </div></div></body></html>
function WarnErr ($scope){    $scope.ifShow = false;    $scope.tipText = ‘‘;    $scope.ifErr = false;    $scope.ifWarn = false;    $scope.showErr = function(){        $scope.ifShow = true;        $scope.tipText = ‘錯誤:‘;        $scope.ifWarn = false;        $scope.ifErr = true;    };    $scope.showWarn = function(){        $scope.ifShow = true;        $scope.tipText = ‘警告:‘;        $scope.ifErr = false;        $scope.ifWarn = true;    }}

<div class="tip" ng-class="{err:ifErr,warn:ifWarn}" ng-show="ifShow">{{tipText}}</div>

  其中,err和warn是待選的類名,":"後面綁定資料,該資料決定了該類名是否會被添加,如果資料的值為true,該類名會被添加,反之則不會被添加

  然後通過給按鈕綁定點擊事件,來改變ifErr和ifWarn的布爾值,改變tip元素的類名,顯示不同的提示框

  

原始狀態

  

 

點擊error按鈕後:

  

 

點擊warning按鈕後:

  

---------------------------------------------------------------------------------------------------------------------------------------------------------------

遺留問題:

1. 沒有說到ng-style的用法

2. 屬性值的運算式執行的結果不僅僅只有以空格分隔css類名的字串,也有css類名數組,和css類名到布爾值的映射.但是後面兩種的用法不詳.

3. 實際的布局中,提示框元素和按鈕元素可能非常遠. 並且不在同一個div裡面,但是他們是需要共用一個控制器的,經過嘗試,兩個div不能使用同一個控制器.這個問題應該如何解決.

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.