Цвет чередующихся строк для каждого нового элемента dom, добавленного в angularjs

0

Я хочу добавить чередующиеся цвета для каждого нового элемента dom, созданного в пользовательской директиве. Когда я нажимаю кнопку "добавить", создается новый элемент DOM, поэтому я хочу один цвет для нечетных строк и другого цвета для четных строк (например: html table stripped colors).

Я мог найти любое решение в сети, и я довольно новичок в угловых. Поскольку я пытаюсь научиться угловатому, я думал, что могу рассказать о нем, задавая вопрос. благодаря

Здесь плункер

Код HTML:

<!DOCTYPE html>
<html lang="en" ng-app="app">
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>Angular.js Query Builder</title>

        <link href="css/bootstrap.min.css" rel="stylesheet">
        <link href="css/styles.css" rel="stylesheet">
  </head>
  <body>
    <div class="container" ng-controller="QueryBuilderCtrl">
    <h1>Angular.js Query Builder</h1>

        <div class="alert alert-info">
            <strong>Example Output</strong><br>
            <span ng-bind-html="output"></span>
        </div>

        <query-builder group="filter.group"></query-builder>
    </div>

    <script type="text/ng-template" id="/queryBuilderDirective.html">
    <div class="alert alert-warning alert-group">
        <div class="form-inline">
            <select ng-options="o.name as o.name for o in operators" ng-model="group.operator" class="form-control input-sm"></select>
            <button style="margin-left: 5px" ng-click="addCondition()" class="btn btn-sm btn-success"><span class="glyphicon glyphicon-plus-sign"></span> Add Condition</button>
            <button style="margin-left: 5px" ng-click="addGroup()" class="btn btn-sm btn-success"><span class="glyphicon glyphicon-plus-sign"></span> Add Group</button>
            <button style="margin-left: 5px" ng-click="removeGroup()" class="btn btn-sm btn-danger"><span class="glyphicon glyphicon-minus-sign"></span> Remove Group</button>
        </div>
        <div class="group-conditions">
            <div ng-repeat="rule in group.rules | orderBy:'index'" class="condition">
                <div ng-switch="rule.hasOwnProperty('group')">
                    <div ng-switch-when="true">
                        <query-builder group="rule.group"></query-builder>
                    </div>
                    <div ng-switch-default="ng-switch-default">
                        <div class="form-inline">
                            <select ng-options="t.name as t.name for t in fields" ng-model="rule.field" class="form-control input-sm"></select>
                            <select style="margin-left: 5px" ng-options="c.name as c.name for c in conditions" ng-model="rule.condition" class="form-control input-sm"></select>
                            <input style="margin-left: 5px" type="text" ng-model="rule.data" class="form-control input-sm"/>
                            <button style="margin-left: 5px" ng-click="removeCondition($index)" class="btn btn-sm btn-danger"><span class="glyphicon glyphicon-minus-sign"></span></button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    </script>

    <script src="http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.18/angular.min.js"></script>
    <script src="http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.18/angular-sanitize.min.js"></script>
    <script src="angular-query-builder.js"></script>
  </body>
</html>

JS:

var app = angular.module('app', ['ngSanitize', 'queryBuilder']);
app.controller('QueryBuilderCtrl', ['$scope', function ($scope) {
    var data = '{"group": {"operator": "AND","rules": []}}';

    function htmlEntities(str) {
        return String(str).replace(/</g, '&lt;').replace(/>/g, '&gt;');
    }

    function computed(group) {
        if (!group) return "";
        for (var str = "(", i = 0; i < group.rules.length; i++) {
            i > 0 && (str += " <strong>" + group.operator + "</strong> ");
            str += group.rules[i].group ?
                computed(group.rules[i].group) :
                group.rules[i].field + " " + htmlEntities(group.rules[i].condition) + " " + group.rules[i].data;
        }

        return str + ")";
    }

    $scope.json = null;

    $scope.filter = JSON.parse(data);

    $scope.$watch('filter', function (newValue) {
        $scope.json = JSON.stringify(newValue, null, 2);
        $scope.output = computed(newValue.group);
    }, true);
}]);

var queryBuilder = angular.module('queryBuilder', []);
queryBuilder.directive('queryBuilder', ['$compile', function ($compile) {
    return {
        restrict: 'E',
        scope: {
            group: '='
        },
        templateUrl: '/queryBuilderDirective.html',
        compile: function (element, attrs) {
            var content, directive;
            content = element.contents().remove();
            return function (scope, element, attrs) {
                scope.operators = [
                    { name: 'AND' },
                    { name: 'OR' }
                ];

                scope.fields = [
                    { name: 'Firstname' },
                    { name: 'Lastname' },
                    { name: 'Birthdate' },
                    { name: 'City' },
                    { name: 'Country' }
                ];

                scope.conditions = [
                    { name: '=' },
                    { name: '<>' },
                    { name: '<' },
                    { name: '<=' },
                    { name: '>' },
                    { name: '>=' }
                ];

                scope.addCondition = function () {
                    scope.group.rules.push({
                        condition: '=',
                        field: 'Firstname',
                        data: ''
                    });
                };

                scope.removeCondition = function (index) {
                    scope.group.rules.splice(index, 1);
                };

                scope.addGroup = function () {
                    scope.group.rules.push({
                        group: {
                            operator: 'AND',
                            rules: []
                        }
                    });
                };

                scope.removeGroup = function () {
                    "group" in scope.$parent && scope.$parent.group.rules.splice(scope.$parent.$index, 1);
                };

                directive || (directive = $compile(content));

                element.append(directive(scope, function ($compile) {
                    return $compile;
                }));
            }
        }
    }
}]);
Теги:

1 ответ

1
Лучший ответ

Некоторые фиктивные css для чередования

.group-conditions div.condition:nth-child(odd){
            border: 1px solid red;
            background: #000;
          }
  • 0
    Как я могу применить только для ввода текстового поля?
  • 0
    Попробуйте .group-conditions div.condition:nth-child(odd) input[type=text] { . Я собирался попробовать это, но по какой-то причине плункер начал рассчитывать на меня. Я не знаю, работает ли это. Я действительно не стал бы ничего менять с точки зрения входных данных для согласованности, но я согласен с зеброй на строках.

Ещё вопросы

Сообщество Overcoder
Наверх
Меню