I have this code:
-
I will start by saying that I really don't like the options for doing this in angular. I can't even say that this is better than the accepted answer, but it does keep the data in the model.
Markup:
{{id}}
Now just $watch the array value and filter when it changes in the controller (make sure to pass the object equality parameter):
$scope.ids = [];
$scope.updateIds = function() {
$scope.ids = $scope.ids.filter(function(id) {
return !!id;
});
};
$scope.$watch('ids', $scope.updateIds, true);
When I started answering this question, I thought the most idiomatic options would be to add an ng-change directive on the input:
Unfortunately this does not work as expected. The UI doesn't update properly when removing values. I also want to point out that you can do this without the repeat directive:
In this case, the $watch is definitely better than adding the ng-change to each input. Finally, here is a working plunkr. The $watch function does end up running twice each time a box is checked or unchecked, but that's really how it has to be!
- 热议问题