1

I'm unable to output a variable within my $scope inside an ng-repeat

The following variables are defined inside my $scope: error_question1 , error_question2 , error_question3

I have the below inside an ng-repeat and I'm trying to assign the span's value to the corresponding variable within my $scope using the ng-repeat's $index.

I can get this working by directly targeting the variable but obviously it duplicates for every item in my ng-repeat like so:

<span class="help-block" ng-show="error_question{{$index + 1}}">{{error_question2}}</span>

However, the way I imagine it working does not work:

<span class="help-block" ng-show="error_question{{$index + 1}}">{{error_question[$index + 1]}}</span>

The [$index+1] appears to be breaking it?

1 Answer 1

4

Note that by doing {{error_question[$index + 1]}} you are basically saying "get me the item at the position $index + 1 of the error_question array". That's not what you want.

Try using a different approach. Instead of having all the error_question1, error_question2, ... error_questionX floating around in the $scope, use an object to encapsulate the errors. Like this:

$scope.errors = {
  question1: ...,
  question2: ...,
  question3: ...,
  ...
};

This way you can use it in the HTML like this:

<span class="help-block" ng-show="errors.question{{$index + 1}}">{{errors['question' + ($index + 1)]}}</span>

Plunker

Sign up to request clarification or add additional context in comments.

Comments

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.