美文网首页
ng-class用法

ng-class用法

作者: 箱猫日和 | 来源:发表于2016-01-10 22:45 被阅读5769次

    ng-class指令有3中操作方式

    方式1: 当它的值为一个字符串时,它就会把用空格分开的字符串加到class中(不推荐,与常用class并无太大差别)

    <div ng-class="{{myclass}}"></div>
    ....
    <script>
    function someController($scope){
    $scope.myclass = "xxx";
    }
    </script>

    方式2: 当值为一个数组时,它每个字符串元素都会被加到class中

    <p ng-class="[style1, style2, style3]">Using Array Syntax</p>
    <input ng-model="style1" placeholder="Type: bold, strike or red">


    <input ng-model="style2" placeholder="Type: bold, strike or red">


    <input ng-model="style3" placeholder="Type: bold, strike or red">
    解释:当我们在样式中定义好bold,strike,red;类的样式后,我们输入这些字符串就会出现效果

    方式3: 当值为一个对象时(key=>value),把value为true的key加到class中

    <div ng-class="{true :'red', false :'green'}[someVariable]"></div>

    这种用法就是说variable为true时,就给元素加上red这个class,如果variable为false就加上green这个class,这个在逻辑比较简单的时候还是蛮好用的。

    下一种适合需要添加多个类的时候,也就是ng-class的值为一个对象

    <p ng-class="{strike: deleted, bold: important, red: error}">Map Syntax Example</p>
    <input type="checkbox" ng-model="deleted"> deleted (apply "strike" class)


    <input type="checkbox" ng-model="important"> important (apply "bold" class)


    <input type="checkbox" ng-model="error"> error (apply "red" class)
    解释:上面代码ng-class就是一个对象,我们把deleted,important,error进行双向数据绑定,当我们在checkbox勾选时,它们变为true,然后对应的key就被加到class中

    <div ng-class {'selected': isSelected, 'car': isCar}">
    当 isSelected = true 则增加selected class,当isCar=true,则增加car class,

    相关文章

      网友评论

          本文标题:ng-class用法

          本文链接:https://www.haomeiwen.com/subject/znpqkttx.html