Ewald Bos
Ewald Bos

Reputation: 1770

NG-Repeat expression value outside the NG-Repeat

i am trying (still learning) to get the value of an NG-Repeat expression outside the NG-Repeat and use it as a value inside a class. This is the NG-Repeat section (i simplified it):

The Classiccds is the array i get from the JSON and the colorcode is a colomn inside, each cd has a different color code.

<div ng-repeat="cd in cds = (classiccds | limitTo:1)">
  <div>{{cd.colorcode;}}</div>
</div>

RESULT: #ffffff

The above works fine, it returns me the colorcode of the first cd in the array but i also would like to use it somewhere else, outside of the array, on the page background (since it returns only one row) as such.

<div style="background-color:{{cd.colorcode}}>
  <div ng-repeat="cd in cds = (classiccds | limitTo:1)">
    <div>{{cd.colorcode;}}</div>
  </div>
</div>

Upvotes: 1

Views: 462

Answers (2)

henrikmerlander
henrikmerlander

Reputation: 1574

If the first value in the array is particularly useful for you, I suggest that you store it in a separate variable on the scope, so you can reuse it easily from multiple locations. Something like this:

function yourCtrl($scope) {
    $scope.cds = //Your array
    $scope.interestingColor = $scope.cds[0].colorcode
}

Then you can use it in your html like this:

<div style="background-color:{{interestingColor}}>
  <div ng-repeat="cd in cds = (classiccds | limitTo:1)">
    <div>{{cd.colorcode;}}</div>
  </div>
</div>

Upvotes: 1

T J
T J

Reputation: 43156

You can simply set this item to your scope in controller, like:

$scope.cd = classiccds[0];

and get away with the ng-repeat itself:

<div style="background-color:{{cd.colorcode}}">
  <div>
    <div>{{cd.colorcode;}}</div>
  </div>
</div>

or you can do:

<div style="background-color:{{(classiccds | limitTo:1)[0].colorcode}}">
  <div ng-repeat="cd in cds = (classiccds | limitTo:1)">
    <div>{{cd.colorcode;}}</div>
  </div>
</div>

Upvotes: 1

Related Questions