Search code examples
angularjsangularjs-ng-checked

angularjs checkbox ng-checked not working


I have the following code :-

<!DOCTYPE html>
<html lang="en">
<head>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.4/angular.min.js"></script>
</head>
<body ng-app="app" ng-controller="ctrl" ng-init="init()">
  <div class="container" style="width:400px">
    <div class="panel panel-default">
      <div class="panel-body">
        <form>
            <div class="form-group">
              <label for="selectedBasket">Select basket :</label>
              <select id="selectedBasket" class="form-control" ng-model="selectedBasket" ng-options="b.name for b in baskets">
              </select>
            </div>
            <div ng-repeat="f in fruits" class="checkbox">
              <label>
                <input type="checkbox" value="" ng-checked="selectedBasket !== null && selectedBasket.items.indexOf(f) !== -1">
                  {{ f }}
              </label>
            </div>
        </form>     
      </div>
    </div>
  </div>

  <script>
  var app = angular.module('app', []);
  app.controller('ctrl', function($scope) {
    $scope.init = function() {
      $scope.baskets = [{'name': 'mary', 'items': ['apple', 'orange']}, {'name': 'jane', 'items': ['banana']}];
      $scope.fruits = ['apple', 'banana', 'cherry', 'orange', 'watermelon'];
      $scope.selectedBasket = null;
    };
  });
  </script>
</body>
</html>

if I select Mary or Jane, I can correctly see the correct items in their basket checked. However if I manually check all the fruits and then look at Mary or Jane, it doesn't exclude the items that are not in their baskets. Why is ng-checked failing?

Bonus question, is it best practise to set selectedBasket to null and checking for null in a directive assuming I want nothing as a default value, is there a better way?


Solution

  • You've got no ng-model in your checkbox so your manual action isn't registered anywhere.
    ng-checked is only used to make a 'slave' checkbox it can take no manual action. My guess is you should use a ng-model initialized to your ng-check value instead of using a ng-checked.

    If you want to keep your ng-checked what you can do is :

    <input type="checkbox" ng-click="selectedBasket.items.push(f)" ng-checked="selectedBasket !== null && selectedBasket.items.indexOf(f) !== -1">
    

    in fact it's still wrong... must be tired, use a toogle function in your ng-click which add or remove the item should be better...