Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 443
daydreamer Avatar asked Jan 30 '26 17:01

daydreamer


1 Answers

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

like image 113
DRobinson Avatar answered Feb 01 '26 05:02

DRobinson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!