ng-options filter in a bs-select cannot access service scope variable

547 Views Asked by At

Update: Plnkr http://plnkr.co/edit/iYmShY6uDaYxktyCYolk?p=preview

I'm creating an angularstrap dropdown with the following code.

{{userService.current.id}} <!-- Outputs correct id (1) -->
<button 
ng-if="userService.current.id || !loginService.isLoggedIn" type="button" class="btn btn-default" 
ng-model="profileService.current" data-placeholder="Profiles" 
ng-options="profile.title for profile in profileService.profiles | 
filter:{userId: userService.current.id}" bs-select>
   Action <span class="caret"></span>
</button>

The filter in the ng-options is not working/not filtering out as expected. If we change the filter to the following:

filter:{userId: 1}

It works as expected. So I am assuming something's wrong with the scope of my situation, but I am starting to feel a bit lost in what is potentially wrong as I am still able to print the correct id in the first row of the example.

Is there something wrong with the scope? Or is there something about filter I'm doing wrong?

1

There are 1 best solutions below

2
On BEST ANSWER

Finally after endless amounts of time, it is resolved. The way I did it is by simply filtering from the controller using $filter. If there's another, better/more proper resolution, I'd like to hear it. It somehow feels a bit wrong to move the filter into the controller when the filter directive already exists..

http://plnkr.co/edit/iYmShY6uDaYxktyCYolk?p=preview

HTML:

    <button type="button" class="btn btn-default" 
ng-model="profileService.current" data-placeholder="Profiles" 
ng-options="profile.title for profile in filteredProfiles" bs-select="">
                Action         <span class="caret"></span>
          </button>

Filter:

.filter('filterProfiles', function() {
  return function(id, profiles) {
  var filteredProfiles = [];
    angular.forEach(profiles, function(value, key) {
      if (value.userId == id) {
        filteredProfiles.push(value);
      }
    });
    return filteredProfiles;
  }
});

Controller:

.controller('HeaderCtrl', function($scope, $filter, userService, profileService) {
$scope.$watch('userService.current', function(newVal, oldVal) {
    $scope.filteredProfiles = $filter('filterProfiles')($scope.userService.current.id, $scope.profileService.profiles);
  });
});