0

Here is a Codepen link

I have multiple buttons that change a CSS attribute for text color. I am able to get this working using static values such as 'blue' or 'red', but I want to access hex code values which are saved in an object within my controller.

<body ng-app="MyApp" ng-controller="AppCtrl">
  <input type="button" value="blue" ng-style="{color: 'blue'}" 
    ng-click="myColor = { color:'blue' }">
  <div ng-repeat="person in people" ng-style="myColor">
    Name: {{ person.name }} <br>
    Birth Year: {{ person.birth }}<p>
  </div>
</body

Here is my controller

var app = angular.module('MyApp', []);
app.controller('AppCtrl', function($scope) {

$scope.colors = [
  { color: 'b1', value: '#000000' },  //black
  { color: 'b2', value: '#000099' },  //blue
  { color: 'r1', value: 'ff0000' },   //red
  { color: 'y1', value: '#ffff00' }   //yellow
];

$scope.people = [
  { name: 'Abraham Lincoln', birth: '1809' },
  { name: 'Benjamin Franklin', birth: '1706' },
  { name: 'George Washington', birth: '1732' }
];

})

I want to change

ng-click="myColor = { color:'blue' }" 

to something along the lines of

ng-click="myColor = { color:'colors[1].value' }

3 Answers3

0

You could call this by calling function on ng-style

<div ng-repeat="person in people" ng-click="person.color = colors[$index].color" ng-style="{color: person.color}">
    Name: {{ person.name }} <br>
    Birth Year: {{ person.birth }}<p>
</div>

Not sure which color should be binding to which person, so I took color based on index

Pankaj Parkar
  • 134,766
  • 23
  • 234
  • 299
0

Looking at the ngStyle docs:

Expression which evals to an object whose keys are CSS style names and values are corresponding values for those CSS keys. Since some CSS style names are not valid keys for an object, they must be quoted.

So you could change it to:

ng-click="myColor = { 'color':colors[1].value }

I found this while searching too: https://stackoverflow.com/a/21364563/643779

Community
  • 1
  • 1
Chewpers
  • 2,430
  • 5
  • 23
  • 30
0

Just use it this way:

<input type="button" value="blue" ng-style="{color: 'blue'}" 
     ng-click="myColor = {color: colors[1].value}">

<input type="button" value="red" ng-style="{color: 'red'}" 
     ng-click="myColor = {color: colors[2].value}">

<input type="button" value="yellow" ng-style="{color: 'yellow'}" 
     ng-click="myColor = {color: colors[3].value}">   

Ignacio Villaverde
  • 1,264
  • 1
  • 11
  • 15