0

I am working on a custom directive in angular (1.4.8) to display an array of items in a vertical list with gradient background colors. I have put together a plunker to demonstrate. The directive takes an initial RGB value (separate values for r,g, and b), converts to HSL, then decreases the saturation value of the HSL for each additional index in the array.

The Good

The directive works fine for a static list of items...

The Bad

...but in my use case items will be added to the array by the user, and the directive should account for changes to the array and re-render the list with the color gradient adjusted accordingly. At the moment I am having a mental block about how to get this part working.

The directive right now sits inside of an <li> that ng-repeats through the array, and I have given it an isolate scope that has knowledge of the array item and the index of the item within that <li> element. I am also passing in the full array as a scope item so that I can $watch for changes to it, which feels hacky and isn't working, to boot:

return {
  ...
  scope: {
    origArray: '=',
    item: '=',
    idx: '@'
  },...
}
  
scope.$watchCollection(function() { return scope.origArray; }, function(newVal) {
  if (newVal) {
    console.log('there was a new item added');
    removeGradient(); // function to set element background to grey
    renderGradient(); // function to set element background to index-appropriate gradient color
  }
});

If you have any thoughts about how I might achieve the dynamic re-rendering, I'd really appreciate it. Thank you!

1 Answer 1

1

The problem is in your listLength variable. It's true that you were tracking the collection but you're not updating listLength that renderGradient is depending on.

So the fix is simple but first of all, there is no need to compute the list's length by querying the dom. You can simply do listLength = scope.origArray.length.

The fix:

// In function decrementHsl, the first line: update listLength
listLength = scope.origArray.length;
...

The updated plunker here.

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

1 Comment

Yep, that's it, thank you! I had the listLength calculated from the DOM nodes prior to adding back in the origArray on scope in the directive and never updated that variable.

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.