【问题标题】:CSS styles doesn't apply when using ngClass使用 ngClass 时 CSS 样式不适用
【发布时间】:2017-02-13 23:26:53
【问题描述】:

我遇到了动态 CSS 更新的问题。这是我的 HTML 代码:

<!DOCTYPE html>
<html lang="en" ng-app="ListItems">
<head>
    <meta charset="utf-8">
    <title>Test project</title>
    <link rel="stylesheet" href="Content/bootstrap.css">
    <link rel="stylesheet" href="Content/style.css">
</head>
<body ng-controller="ListController as list">
    <h1>To-do list</h1>

    <div id="main">
        <article ng-repeat="item in items track by $index" ng-class="{{item.IsCompleted ? 'completed' : 'uncompleted'}}">
            <p>{{item.Description}}</p>
            <footer>
                <small>
                    Is completed: <input type="checkbox" ng-checked="{{item.IsCompleted}}" ng-click="complete($index)" />
                </small>
            </footer>
        </article>
    </div>

    <script src="Scripts/angular.js"></script>
    <script src="Scripts/jquery-3.1.1.js"></script>
    <script src="Scripts/script.js"></script>
</body>
</html>

如果项目完成,现在我想应用以下 css 样式:

.completed {
    background-color: red;
}

但是什么也没发生。

【问题讨论】:

  • 查看 F12 调试器并查看是否应用了 tstyles。你也看到了原因
  • 我的article 获得了completed 课程,但我没有在页面上看到任何可见的变化。
  • ng-class 的语法无效。
  • @JosephKatzman 无需在ng-class 中使用{{}},只需在@lin 回答中使用表达式或JSON
  • @PankajParkar 欢呼 m8 =)

标签: html css angularjs ng-class


【解决方案1】:

尝试使用正确的ng-class 语法并确保.completed CSS 类由于您的CSS 声明而可用。这是一个简单的工作fiddle,它将为您提供帮助。将其与您的解决方案进行比较。请看一下AngularJS的ng-class documentation

<article ng-repeat="item in items track by $index" 
         ng-class="{'completed': item.IsCompleted, 'uncompleted': !item.IsCompleted}">
    <p>{{item.Description}}</p>
    <footer>
        <small>
            Is completed: 
            <input type="checkbox" 
                   ng-checked="{{item.IsCompleted}}" 
                   ng-click="complete($index)" />
        </small>
    </footer>
</article>

【讨论】:

  • 嗯。谢谢。你是对的,但怎么可能呢?为什么我的示例不起作用?
【解决方案2】:

您需要更改 ng-class 语法。简单点:

<article ng-repeat="item in items track by $index" ng-class="{'completed': item.IsCompleted}">

【讨论】:

    猜你喜欢
    • 2021-01-30
    • 2021-09-22
    • 1970-01-01
    • 1970-01-01
    • 2020-08-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多