Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I've got an object in my $scope that contains a bunch of details about, say, an election. This object includes a voters array of objects, each with an _id:

$scope.election = {
  voters: [
    { _id: '123' },
    { _id: '456' },
    { _id: '789' }
  ]
}

Also in my scope I have details about the currently logged in user:

$scope.user = { _id: '456' }

How can I bind ng-disabled to the presence of $scope.user._id in the array of objects $scope.voters?

What I've Tried

I have success simply displaying the presence of $scope.user._id in $scope.election.voters like this (Jade syntax):

pre(ng-bind="election.voters | filter:{user._id} | json")

When the current user is among the voters, they get displayed. When they're not among the voters, I get an empty array. That seems quite close to what I want.

But using the same filter (sans | json) with ng-disabled, I get the Angular Infinite $digest loop error.

Is this situation too complicated? Should I move it to a $filter? If so, how would I go about making it generic enough to be useful in a number of situations (if that's even feasible)?

share|improve this question

1 Answer 1

up vote 0 down vote accepted

Can run a simple filter right in controller, or using app.filter('filterName', func...) create a custom filter you can use in markup

$scope.userIsVoter = function() {
        return $scope.election.voters.filter(function(el) {
          return el._id == $scope.user._id;
        }).length
      }
<button ng-disabled="userIsVoter()">Do Something</button>
share|improve this answer
    
This seems like the way to go, but I'm running into a complication. My $scope.election is actually set as the result of a Restangular call. $scope.userIsVoter() gets called before the call finishes, and needs to be checked again by Angular afterwards. Can I trigger that check, or would the approach need to change? –  Collin Allen Nov 15 '13 at 19:27
    
can set a $watch for voters, use a scope variable for ng-disabled and set that variable within the watch $disabledVariable= $scope.userIsVoter() –  charlietfl Nov 15 '13 at 19:44

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.