Как связать со списком значений флажков с AngularJS?

Вот моя реализация в Java:

public class SpiralPrint {
static void spiral(int a[][],int x,int y){

    //If the x and y co-ordinate collide, break off from the function

    if(x==y)
        return;
    int i;

    //Top-left to top-right

    for(i=x;i<y;i++)
        System.out.println(a[x][i]);

    //Top-right to bottom-right 

    for(i=x+1;i<y;i++)
        System.out.println(a[i][y-1]);

    //Bottom-right to bottom-left

    for(i=y-2;i>=x;i--)
        System.out.println(a[y-1][i]);

    //Bottom left to top-left

    for(i=y-2;i>x;i--)
        System.out.println(a[i][x]);

    //Recursively call spiral

    spiral(a,x+1,y-1);

}

public static void main(String[] args) {

    int a[][]={{1,2,3,4},{5,6,7,8},{9,10,11,12},{13,14,15,16}};
    spiral(a,0,4);
    /*Might be implemented without the 0 on an afterthought, all arrays will start at 0 anyways. The second parameter will be the dimension of the array*/ 

    }

}
656
задан Peter Mortensen 7 January 2017 в 15:16
поделиться

4 ответа

Вам не нужно писать весь этот код. AngularJS будет поддерживать синхронизацию модели и флажков, просто используя ngTrueValue и ngFalseValue

Codepen здесь: http://codepen.io/paulbhartzog/pen/kBhzn

Фрагмент кода:

<p ng-repeat="item in list1" class="item" id="{{item.id}}">
  <strong>{{item.id}}</strong> <input name='obj1_data' type="checkbox" ng-model="list1[$index].data" ng-true-value="1" ng-false-value="0"> Click this to change data value below
</p>
<pre>{{list1 | json}}</pre>
4
ответ дан Paul B. Hartzog 7 January 2017 в 15:16
поделиться

Еще одна простая директива может быть такой:

var appModule = angular.module("appModule", []);

appModule.directive("checkList", [function () {
return {
    restrict: "A",
    scope: {
        selectedItemsArray: "=",
        value: "@"
    },
    link: function (scope, elem) {
        scope.$watchCollection("selectedItemsArray", function (newValue) {
            if (_.contains(newValue, scope.value)) {
                elem.prop("checked", true);
            } else {
                elem.prop("checked", false);
            }
        });
        if (_.contains(scope.selectedItemsArray, scope.value)) {
            elem.prop("checked", true);
        }
        elem.on("change", function () {
            if (elem.prop("checked")) {
                if (!_.contains(scope.selectedItemsArray, scope.value)) {
                    scope.$apply(
                        function () {
                            scope.selectedItemsArray.push(scope.value);
                        }
                    );
                }
            } else {
                if (_.contains(scope.selectedItemsArray, scope.value)) {
                    var index = scope.selectedItemsArray.indexOf(scope.value);
                    scope.$apply(
                        function () {
                            scope.selectedItemsArray.splice(index, 1);
                        });
                }
            }
            console.log(scope.selectedItemsArray);
        });
    }
};
}]);

Контроллер:

appModule.controller("sampleController", ["$scope",
  function ($scope) {
    //#region "Scope Members"
    $scope.sourceArray = [{ id: 1, text: "val1" }, { id: 2, text: "val2" }];
    $scope.selectedItems = ["1"];
    //#endregion
    $scope.selectAll = function () {
      $scope.selectedItems = ["1", "2"];
  };
    $scope.unCheckAll = function () {
      $scope.selectedItems = [];
    };
}]);

И HTML:

<ul class="list-unstyled filter-list">
<li data-ng-repeat="item in sourceArray">
    <div class="checkbox">
        <label>
            <input type="checkbox" check-list selected-items-array="selectedItems" value="{{item.id}}">
            {{item.text}}
        </label>
    </div>
</li>

Я также включаю Плункер: http://plnkr.co/edit/XnFtyij4ed6RyFwnFN6V?p=preview

5
ответ дан Adrian Stanescu 7 January 2017 в 15:16
поделиться

Использование строки $index может помочь использовать хэш-карту выбранных значений:

<ul>
    <li ng-repeat="someItem in someArray">
        <input type="checkbox" ng-model="someObject[$index.toString()]" />
    </li>
</ul>

Таким образом, объект ng-модели обновляется ключом, представляющим индекс.

$scope.someObject = {};

Через некоторое время $scope.someObject должно выглядеть примерно так:

$scope.someObject = {
     0: true,
     4: false,
     1: true
};

Этот метод не будет работать во всех ситуациях, но его легко реализовать.

11
ответ дан Peter Mortensen 7 January 2017 в 15:16
поделиться

На основе ответов в этой теме я создал директиву checklist-model , которая охватывает все случаи:

  • простой массив примитивов
  • массив объектов (выберите идентификатор или весь объект)
  • итерация свойств объекта

Для случая с темой-инициатором это будет:

<label ng-repeat="fruit in ['apple', 'orange', 'pear', 'naartjie']">
    <input type="checkbox" checklist-model="selectedFruits" checklist-value="fruit"> {{fruit}}
</label>
66
ответ дан vitalets 7 January 2017 в 15:16
поделиться
Другие вопросы по тегам:

Похожие вопросы: