1

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)?

1 Answer 1

1

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>
Sign up to request clarification or add additional context in comments.

2 Comments

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?
can set a $watch for voters, use a scope variable for ng-disabled and set that variable within the watch $disabledVariable= $scope.userIsVoter()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.