angular学习笔记(九)-css类和样式2

在上一个例子中,元素的类名使用拼接的方法,这样,类名中就不得不带有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不能使用同一个控制器.这个问题应该如何解决.

posted @ 2014-05-09 16:04  诗&远方  阅读(1910)  评论(0编辑  收藏  举报