4

I have an ng repeat repeating data. - Some of data.image (src) is null, and those with src=null are not to be repeated.

I solved it with a simple ng-if.

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

      <div class="ImageContainer">
        <img ng-src="{{::data.image}}" ng-if="data.image != null" />
      </div>
      <div class="LabelContainer">
        <p>
          {{::data.label}}
        </p>
      <div>
<div>

but from debugging I noticed this cost me around 500 watchers. Any obvious way to accomplish what im trying without the ng-if or a major JS vanilla function ?

Anders Pedersen
  • 2,255
  • 4
  • 25
  • 49
  • why not return data where src is not null before having angular process it? – zerohero Apr 21 '16 at 12:05
  • @zerohero I'm repeating labels and images, some labels does not have an image attached. – Anders Pedersen Apr 21 '16 at 12:06
  • 1
    again, easily solved by manipulating the data to have the src (if null) point to a 1x1 pixel image or even a placeholder image? why spin up 500+ watchers if you could easily solve this in the data? – zerohero Apr 21 '16 at 12:15
  • your right, i should probably just use an 'invisible' image placeholder. thanks – Anders Pedersen Apr 21 '16 at 12:17
  • Does `data.label.length` need to be watched? Otherwise, you could use `ng-repeat="data in ::data"` as suggested [in the answer to this question](http://stackoverflow.com/q/25523991/5520354). – C14L Apr 21 '16 at 12:29
  • unfortunately it does yes :) - I've tried to have one way bindings where ever i can get away with it. – Anders Pedersen Apr 21 '16 at 14:25

2 Answers2

2

You could filter the list in your controller so you have a method which returns all of the items in the collection where the image property isn't null and bind your repeat to that function.

DoctorMick
  • 6,703
  • 28
  • 26
  • check out my updated code snippet. the labels and image ordering still need to match, - so if i just weed out all the nulls the lists no longer has the same length. – Anders Pedersen Apr 21 '16 at 12:12
  • I've checked the snippet and can't see where the problem is, if you exclude those without a null image you won't get a label for it either so you won't have a problem. How is your data retrieved/populated? – DoctorMick Apr 21 '16 at 12:21
1

You can apply one way binding on ng-if that way you can reduce few more watchers.

I agreed with @DoctorMick, filter will reduce number for loop, watchers and it will be fast as well. But if you have some other data along with image and you want to show that data then it will not solve your purpose.

Rahul
  • 685
  • 5
  • 15