search

Home  >  Q&A  >  body text

angular.js - How to use ng-repeat's $index to select different styles

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="http://apps.bdimg.com/libs/angular.js/1.4.6/angular.min.js"></script>
</head>
<body ng-app="myApp" ng-controller="myCtrl">

<h1 style="color:contents[$index].color" ng-repeat="x in records">{{x.name}}+    {{contents[$index].color}}</h1>

<script>
var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope) {
  $scope.records = [
  {name:"T"},
  {name:"D"},
  {name:"Z"}
  ];
$scope.contents=[
    {color:"red"},
    {color:"blue"},
    {color:"yellow"}
]
});

</script>

This is the test code. Below is the test rendering. How can I make the color of the words change accordingly?

天蓬老师天蓬老师2796 days ago532

reply all(1)I'll reply

  • 淡淡烟草味

    淡淡烟草味2017-05-15 17:03:45

    Use the built-in ng-style directive, which accepts an object as a parameter.

    So, js does not need to be changed, html is written like this:

    <h1 ng-style="contents[$index]" ng-repeat="x in records">{{x.name}} + {{contents[$index].color}}</h1>

    reply
    0
  • Cancelreply