angularJs中的CSS类和样式

来源:互联网 发布:java多线程网络编程 编辑:程序博客网 时间:2024/06/14 17:55

假设有以下的css代码:

.menu-disabled-true{    color:gray;}

使用angular你就可以这样写:

<div ng-controller = "myController">    <ul>        <li class = "menu-disabled-{{isdisabled}}" ng-click = "stun()">Stun</li>        .        .        .    </ul></div>

根据需要通过控制器来设置isdisabled属性了、、

function myController($scope){    $scope.isdisabled = false;$scope.stun = function(){    $scope.isdisabled  = !$scope.isdisabled ;    }}

使用ng-class和ng-style这两个指令都可以接受一个表达式,表达式的结果可能是如下取值之一:
①. 表示css类名的字符串
②. css类名数组
③. css类名到布尔值的映射

假设你现在希望在应用头部的固定位置向用户显示错误的警告信息,使用ng-class指令:

.error{    background-color: red;}.warning{    background-color: yellow;}<div ng-controller = "HeaderController">    <div ng-class = "{error: isError, warning: isWarning}">{{messageText}}</div>    <button ng-click = "showError()">Simulate Error</button>    <button ng-click = "showWarning()">Simulate Warning</button></div>function HeaderController($scope){    $scope.isError = false;    $scope.isWarning = false;    $scope.showError = function(){    $scope.messageText = "This is an error!";    $scope.isError = true;    $scope.isWarning = false;    };  $scope.showWarning = function(){    $scope.messageText = "Just a warning, please carry on!";    $scope.isError = false;    $scope.isWarning = true;    };}

还可以将选中的行高亮显示,比方说构建一个餐馆名录,想把用户点击的那一行高亮显示:

.selected{    background-color:lightgreen;}<table ng-controller = "RestaurantTableController">    <tr ng-repeat = "restaurant in directory" ng-click = "selectedRestaurant($index)" ng-class = "{selected: $index == selectedRow}">    <td>{{restaurant.name}}</td>    <td>{{restaurant.cuisine}}</td></tr></table>function RestaurantTableController($scope){    $scope.directory = [    {name: "restaurantA", cuisine: "BBQ"},    {name: "restaurantB", cuisine: "salads"},    {name: "restaurantC", cuisine: "seafood"}    ];    $scope.selectedRestaurant = function(index){        $scope.selectedRow = index;    };}

把ng-class设置为{selected : index = selectedRow}.这样做的效果就是,当模型属性selectedRow的值等于ng-repeat中的index时,selected样式就会被设置到那一行上。还会设置一个ng-click指令,用来告诉控制器用户点击了哪一行。

原创粉丝点击