简体   繁体   中英

Checkbox ng-click fired twice

I am trying fill some checkboxes dynamically and use the selected items to filter the data.

My HTML

<div class="form-group" ng-repeat="category in categories">
  <label class="checkbox" >
    <input type="checkbox" ng-model="selection.ids[category.code]" id="{{category.code}}" 
           ng-click="toggleSelection(category)"
           />
    {{category.description}}
  </label>
</div>
<div class="form-group">
  <button type="submit" ng-click="filterSubmit();" class="btn btn-default">
    <span class="glyphicon glyphicon-search"></span> Filter
  </button>
</div>

In my controller I am using this javascript, not unlike most other examples I've seen.

$scope.toggleSelection = function (category) {
  var idx = $scope.selection.indexOf(category);
  console.log('start '+ idx);

  // is currently selected
  if (idx > -1) {
    $scope.selection.splice(idx, 1);
  }
  // is newly selected
  else {
    $scope.selection.push(category);
  }
};

Sadly enough I see the console logged twice , once with -1, once with 0. So I end up with no selected checkbox.

When I build the app using grunt and place it on the webserver it works correctly, but when I run it using grunt serve it keeps calling the controller twice.

As Brian mentions in a comment :

How is your code compiled differently with grunt serve versus for production? From the fact that it's being called twice in one instance but not the other points to your code being included twice when it gets concatenated via grunt serve, but not when built for prod.

Grunt was set differently at different environments. Fixing that, solved the problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM