根据用户选择的值,使用ng-class添加类

时间:2015-08-12 05:32:25

标签: jquery angularjs

从下拉列表中选择值时,我使用了angular来显示内容。

我需要在选择值时将div添加到div。因此,当从下拉列表中选择某些值时,请将某些css类添加到div。

我知道它可以通过ng-class完成,但我很难在我的案例中使它成功。

如何根据用户从使用ng-class下拉列表中选择的值添加css类?

示例在案例上添加类:

selections[0] == items[0].id && selections[1] == items[0].id && selections[2] == itemsb[0].id

这是代码:

<div class="ticketsystem" ng-controller="Main" ng-app>
    <div>selections = {{selections}}</div>

    <div class="choose">
        <p>Choose</p>
        <p>From</p>
        <select ng-model="selections[0]" ng-options="i.id as i.name for i in items">
            <option value=""></option>
        </select>
        <p>To</p>
        <select ng-model="selections[1]" ng-options="i.id as i.name for i in items">
            <option value=""></option>
        </select>
        <p>Group</p>
        <select ng-model="selections[2]" ng-options="i.id as i.name for i in itemsb">
            <option value=""></option>
        </select>
    </div>


    <div class="show-this-3" ng-show="
    selections[0] == items[1].id && selections[1] == items[1].id && selections[2] == itemsb[0].id || 
    selections[0] == items[0].id && selections[1] == items[0].id && selections[2] == itemsb[0].id || 
    selections[0] == items[2].id && selections[1] == items[2].id && selections[2] == itemsb[0].id">
        <p>Tickets</p>
        <div class="content">
            <div class="ticket">Ticket 1</div>
            <div class="ticket">Ticket 2</div>
        </div>
    </div>

</div>
<!-- Add class to this div -->
<div ng-class="add-class">Text</div>

这是jsfiddle example

2 个答案:

答案 0 :(得分:1)

这样的事情怎么样?基本上我只是根据您的a-a-a示例将类值添加到项目对象中,所以我假设您希望items数组的第一项为a,第二项b,那些当然可以以你需要的方式改变。

http://jsfiddle.net/agenjn1c/3/

控制器:

$scope.items = [{
    id: 'id-1',
    name: 'A',
    classValue: 'a'},
{
    id: 'id-2',
    name: 'B',
    classValue: 'b'}];

$scope.getDivClass = function() {
    function findClass(collection, id) {
        var item = _.find(collection, function(item) {
            return item.id === id;
        })
        if (item !== undefined) return item.classValue;
    }
    var first = findClass($scope.items, $scope.selections[0]);
    var second = findClass($scope.items, $scope.selections[1]);
    var third = findClass($scope.itemsb, $scope.selections[2]);
    return first + "-" + second + "-" + third;
}

HTML:

<div ng-class="getDivClass()">Text</div>

答案 1 :(得分:0)

做这样的事情:

<div ng-class="{'add-class': selections[0] === 'xyz'}">Text</div>

如果您对问题更精确,我可以编写更具体的代码。

检查是否选择了每个下拉列表,然后分配一个类:

<div ng-class="{'add-class': selections[0] && selections[1] && selections[2]}">Text</div>