Maybe change this to a while? e.g.
```
level = 0
while $scope["selected#{level}"]?.id
  $scope.meshHeadingIds.push $scope["selected#{level}"].id
  level += 1
```