3

This is how I populate the Table and attach checkbox to controller

    <tr ng-repeat="key in queryResults.userPropNames">
      <td><input type="checkbox"
                 data-ng-checked="selectedKeys.indexOf(key) != -1"
                 data-ng-click="toggleSelect(key)">

      </td>
      <td>{{key}}</td>
      <td ng-repeat="user in queryResults.users">
        {{user.properties[key]}}
      </td>
    </tr>

This is how my HTML for button looks

  <div>
    <span ng-if="!validKeys" class="button-terminal primary save-user-keys"
          data-disabled="false">Save Keys</span>
    <span ng-if="validKeys" class="button-terminal primary save-user-keys"
          data-ng-click="saveUserKeys()">Save Keys</span>
  </div>

and my Controller looks like

$scope.toggleSelect = function (attribute) {
    if ($scope.selectedKeys.indexOf(attribute) === -1) {
        $scope.selectedKeys.push(attribute);
    } else {
        $scope.selectedKeys.splice($scope.selectedKeys.indexOf(attribute), 1);
    }
};

$scope.saveUserKeys = function() {
    $scope.customAttributes.mappingForUser = $scope.selectedKeys;
    $scope.saveMappings();
};

$scope.validKeys = !!$scope.selectedKeys;

But my button is always enabled, even if I de-select all the checkboxes

What is wrong with this code?

Thank you

daydreamer
  • 87,243
  • 191
  • 450
  • 722
  • Won't `selectedKeys` be an empty Array? `[]` is truthy, so the `ng-if` will resolve true, unless you do `ng-if="validKeys.length"` – DRobinson May 20 '15 at 18:32

2 Answers2

2

$scope.selectedKeys is an Array, even when no keys are selected. However empty Arrays are truthy (!![] // => true).

One fix would be to check the length of selectedKeys instead:

$scope.validKeys = $scope.selectedKeys && $scope.selectedKeys.length;

Alternatively, if assigning validKeys was just an attempt to get the view to render correctly, on the view you could just update the ngIf to ng-if="selectedKeys.lengh"

DRobinson
  • 4,441
  • 22
  • 31
0

If you print validKeys (i.e. {{validKeys}}, do you see it changing between true/false? Also, if I understand this correctly, you should be testing for the length of validKeys - if higher than 0, enable the button, otherwise disable it.

Giliar Perez
  • 106
  • 2