使用ngClass更改单个单元格颜色

时间:2016-12-11 04:32:12

标签: angularjs

我在这里使用ngClass很难,因为我是棱角分明的新手。我有一个表设置,使用ng-repeat从数据库动态生成行,其中span和input元素基于编辑/不编辑单元格隐藏/显示(想象一下microsoft excel)。

<tr>
  <th class="row_head">Row Title</th>
  <td ng-click="edit = true" ng-repeat="item1 in JSONobject | orderBy: '_id'" >
     <span ng-hide="edit">{{ item1.key.value1 }}</span>
     <input ng-show="edit" class="editing-cell" ng-model="item1.key.value1" ng-blur="edit = false; " ng-enter="saveData(item1._id, item1.key); edit = false" type="text" />
  </td>
</tr>

<tr>
  <th class="row_head">Row Title</th>
  <td ng-click="edit = true" ng-repeat="item2 in JSONobject | orderBy: '_id'" >
     <span ng-hide="edit">{{ item2.key.value2 }}</span>
     <input ng-show="edit" class="editing-cell" ng-model="item2.key.value2" ng-blur="edit = false; " ng-enter="saveData(item2._id, item2.key); edit = false" type="text" />
  </td>
</tr>

等等。

我想将它设置为模糊(数据未保存),单元格变为红色,或者在保存时变为绿色。

我正在使用ngClass遇到的问题是,如果我选择:

ng-class="{'saved': saved, 'notSaved': notSaved}"

它会更改每个单元格的背景颜色,而不仅仅是编辑的单元格。

我没有使用ng-hide和ng-show这个问题,即使它们似乎与更改“编辑”的布尔值类似。他们仍然坚持他们的特定细胞。

任何帮助都将不胜感激。

2 个答案:

答案 0 :(得分:0)

您应该了解表单样式的工作原理。

以下类添加到输入字段或从中删除

ng-untouched The field has not been touched yet
ng-touched The field has been touched
ng-pristine The field has not been  modified yet
ng-dirty The field has been modified
ng-valid The field content is valid
ng-invalid The field content is not valid
ng-valid-key One key for each validation. Example: ng-valid-required, useful when there are more than one thing that must be validated
ng-invalid-key Example: ng-invalid-required

以下类已添加到表单中或从表单中删除:

ng-pristine No fields has not been modified yet
ng-dirty One or more fields has been modified
ng-valid The form content is valid
ng-invalid The form content is not valid
ng-valid-key One key for each validation. Example: ng-valid-required, useful when there are more than one thing that must be validated
ng-invalid-key Example: ng-invalid-required
The classes are removed if the value they represent is false.

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>  
<style>
form.ng-pristine {
    background-color:lightblue;
}
form.ng-dirty {
    background-color:pink;
}
</style>
<body ng-app="">

<form name="myForm">
<p>Try writing in the input field:</p>

<input name="myName" ng-model="myName" required>

<p>The form gets a "ng-dirty" class when the form has been modified, and will therefore turn pink.</p>
</form>

</body>
</html>

答案 1 :(得分:0)

我的问题是对自定义指令了解不够。我现在已经弄明白了

.directive('isSaved', function(){
return {
    link: function(scope, elem, attr) {
        scope.notSaved = function(){
            attr.$set('class', 'notSaved');
        };
        scope.saved = function(){
            attr.$set('class', 'saved');
        };

      }
  };
});