daydreamer
daydreamer

Reputation: 91949

ng-if not working as expected

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

Upvotes: 3

Views: 153

Answers (2)

DRobinson
DRobinson

Reputation: 4471

$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"

Upvotes: 2

Giliar Perez
Giliar Perez

Reputation: 106

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.

Upvotes: 0

Related Questions