AngularJs,将颜色更改为(重复)列表中的单个项目

时间:2016-03-07 16:27:13

标签: angularjs list

我是angularjs的新手。这是我的问题:

这是我的数据:

$scope.products = [
                       {item: "Milk", alreadyTook: false},
                       {item: "Bread", alreadyTook: false},
                       {item: "Cheese", alreadyTook: true}
                      ];

这是我的控制者:

var mymodal = angular.module('app', []);
mymodal.controller("myCtrl", function($scope) {

    $scope.toggleSelection = function(itemObject) { 
        itemObject.item=itemObject.item;
        itemObject.alreadyTook=!itemObject.alreadyTook;
    };
});

这是我的HTML:

<div ng-app="app" ng-cloak ng-controller="myCtrl">

<ul class="w3-ul">
    <li ng-repeat="x in products" ng-click="toggleSelection(x)" ng-style="{ 'color' : ({{x.alreadyTook}}) ? 'red' : 'black' }">{{x.item}}
    </li>
</ul>

我需要设置/取消设置所选单个文本的前景色(通过鼠标点击);我不想使用纯粹的js或jquery。 谢谢。

3 个答案:

答案 0 :(得分:3)

您可以有条件地申请课程:

ng-class="{taken: x.alreadyTaken}"

的CSS:

#mylist li {color: black}
#mylist li.taken{color: red}

从我的头脑中,我无法想象ng-style的用例,我不会认为这是不好的做法。

将ng-class与适当的类一起使用比在模板中设置样式更容易维护。

答案 1 :(得分:3)

您只是误认为x.alreadyTook,您不需要插值,只需使用{{ }}而不使用ng-style="{ 'color' : (x.alreadyTook) ? 'red' : 'black' }"

Store.joins(:manager)

工作JSFiddle

答案 2 :(得分:2)

删除{{}},如下所示:

current_identifier = nil

(firstrow.to_i..lastrow.to_i).each do |row|

  if current_identifer != data.at(row).dln # current row is new identifier
    if current_identifier # this is not the first row
       puts "Last row for #{current_identifier} is #{row-1}\n"
    end
    current_identifier = data.at(row).dln # remember current row
  end

  # we need to track the last row as the last for the current identifier
  puts "Last row for #{current_identifier} is #{lastrow.to_i}\n"