Veer Veer - 2 months ago 8x
AngularJS Question

Angular js: Change the font color and image, based on json response

Suppose their is an external json file:

{"threat": [{"level": "Low"},{"level": "Medium"},{"level": "high"}]}

And following is the HTML code:

<body ng-app="myApp">
<h1>Page Title</h1>
<img src="images/status.jpg">
<p>change color</p>

How i can change image and p tag color? depending upon the json response (threat level).

  1. High:red

  2. Low:green

  3. medium:orange

I am new to Angular js, tried some methods like ng-style and ng-if to change the styles. But dint work out.

I am trying to do something like this:

function MyController($scope, $http) {
// Simple GET request example:
method: 'GET',
url: 'data/color.json'
}).then(function successCallback(response) {
// this callback will be called asynchronously
// when the response is available
return response;
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
return response;

But i am getting undefined in console instead of response.

After getting response I have to check how to change image and text color?depending upon response high, Low and medium.


you have to make 3 css class for font-color

.red {
  color: 'red';
.green {
  color: 'green';
.orange {
  color: 'orange';

now you can do it in two different ways,

Option 1)

in js do:

$scope.selectedItem = ({Low:{
    url: '1images/status.jpg',
    class: 'green'
    url: '2images/status.jpg',
    class: 'orange'
    url: '3images/status.jpg',
    class: 'red'

in HTML do

<body ng-app="myApp">
   <h1>Page Title</h1>
   <img src="{{selectedItem.url}}">
   <p class="{{selectedItem.class}}">change color</p>

Option 2)

In html use ng-class and ng-if:

<body ng-app="myApp">
  <h1>Page Title</h1>
  <img src="url1" ng-if="response.level === 'Low'">
  <img src="url2" ng-if="response.level === 'Medium'">
  <img src="url3" ng-if="response.level === 'High'">
  <p ng-class="{'red': response.level === 'High', 'orange': response.level === 'Medium', 'green': response.level === 'Low'}">change color</p>