0

So, I have this ng-repeat where I call a class to set the text if the text attribute has content. This text attribute which in turn will be get binded in the html side. However, only the last variable that got set will be reflected even with the previous data in the repeater.

Here is my code

<div ng-repeat="x in data">
     <p ng-init="setText(x.text);">{{ ::titleText}}</p>
</div>

$scope.setText = function(text) {
        $scope.titleText = text;
        if (!$scope.titleText) {
            $scope.titleText = 'Blabla';
        }
};

For example if i have

x[0].text = '';
x[1].text = '';
x[2].text = '';
x[3].text = 'Test';

My expectations would be that x[0-2].text would equals to 'Blabla' but it ends up being 'Test'

I am not sure how to solve this issue.

somnia06
  • 11
  • 5

2 Answers2

0

Believe your use of ng-init is improper. Per the docs:

This directive can be abused to add unnecessary amounts of logic into your templates. There are only a few appropriate uses of ngInit, such as for aliasing special properties of ngRepeat, as seen in the demo below; and for injecting data via server side scripting. Besides these few cases, you should use controllers rather than ngInit to initialize values on a scope.

Potentially related is this question re. ng-init within ng-repeat.

Community
  • 1
  • 1
Sensei James
  • 2,617
  • 30
  • 36
0

I'm not sure if I understand your question (what do you mean by 'class'? css class? JS class?).

This SO may be pertinent.

OTOH, if you are trying to set a DOM element's class per what an array element attribute contains within an ng-repeat, this is how you can do it (pseudo code):

<div ng-repeat="x in data">

  <pre ng-class="{'class-a':x.text ==='whatever-a', 'class-b':x.text==='whatever-b'}"></pre>
</div>

Something along these lines, where class-a and class-b are defined in your css.

Hope this helps.

Community
  • 1
  • 1
MoMo
  • 1,836
  • 1
  • 21
  • 38