ngClass无法正确呈现

时间:2015-02-21 15:45:17

标签: angularjs ng-class

我正在加载一个待办事项列表,每个待办事项都有一个标志字段,如果为真,ng-class应该适用。如果我使用ng-class,则会将数据加载到页面中ng-class="{'completed': todo.isCompleted=='true'}",但是当我使用复选框时它不会起作用。

另一方面,如果我改为使用ng-class="{'completed': todo.isCompleted==true}"true上没有引号),则会在开头加载数据而不应用ng-class,意味着加载所有数据就像它们是假的,但是在使用复选框时它可以正常工作。

它一直让我发疯,无法弄清楚原因。

<ul id="todo-list">
    <li ng-repeat="todo in todos" ng-class="{'completed': todo.isCompleted==true}" class="editing">
        <div class="view" >
            <input class="toggle" type="checkbox" ng-click="complete(todo)" ng-model="todo.isCompleted" ng-checked="{{todo.isCompleted}}">
            <label ng-hide="isEditing" ng-dblclick="isEditing = !isEditing">{{todo.title}}</label>
            <button class="destroy" ng-click="remove(todo)"></button>
        </div>
        <input class="edit" ng-show="isEditing" ng-model="todo.title" ng-blur="isEditing = !isEditing;edit(todo);">
    </li>
</ul>

控制器

$scope.complete = function(todo) {
    $scope.insertTodo(todo, UPDATE);
};

感谢任何帮助。

2 个答案:

答案 0 :(得分:1)

您是否尝试过更改

ng-class="{'completed': todo.isCompleted==true}"

ng-class="{'completed': todo.isCompleted}"

或者其中一个

ng-class="todo.isCompleted ? 'completed' : ''"  
ng-class="{true: 'completed', false: ''}[todo.isCompleted]"

答案 1 :(得分:1)

因此,您的服务器似乎将布尔值值作为字符串返回,这就是您的绑定不起作用的原因...

您可以更改服务器的返回值(首选)或将ng-true-valueng-false-value添加到您的复选框,并使用“ng-class保持绑定”字符串比较:

<ul id="todo-list">
    <li ng-repeat="todo in todos" ng-class="{'completed': todo.isCompleted=='true'}" class="editing">
        <div class="view" >
            <input class="toggle" type="checkbox" ng-click="complete(todo)" ng-model="todo.isCompleted" ng-checked="{{todo.isCompleted}}" ng-true-value="'true'"  ng-false-value="'false'">
            <label ng-hide="isEditing" ng-dblclick="isEditing = !isEditing">{{todo.title}}</label>
            <button class="destroy" ng-click="remove(todo)"></button>
        </div>
        <input class="edit" ng-show="isEditing" ng-model="todo.title" ng-blur="isEditing = !isEditing;edit(todo);">
    </li>
</ul>

希望有所帮助