NewBoy
NewBoy

Reputation: 1144

How to get data from a JSON file using Angular's ng-style

I am making attempts to style elements based off the attributes highlighted in my JSON file. I am currently using ng-styleto call properties within the JSON objects

ng-style="{color: colors.color }"

The example above doesn't seem to be doing in regards to targeting styling the nodes on my DOM

Does any know how to resolve this issue.

{
 "colors": [
 {
"color": "red",
"value": "#f00",
"message": "Simple message"
 },
 {
"color": "green",
"value": "#0f0",
"message": "Message with <strong>HTML</strong> tags"
 },
 {
"color": "blue",
"value": "#00f",
"message": "Am I going to work? I should not! <script>alert('Hello!');</script>"
}]
}

HTML

<ul class="block-elements">
  <li ng-repeat="details in colors">
   <button ng-click="popupBtn()" ng-style="{color: colors.color }">Click Me</button>
  </li>
</ul>

CONTROLLER

"use strict";

var app = angular.module('nApp');

app.service("dataService", function ($http, $q){
var deferred = $q.defer();
$http.get('app/data/data.json').then(function (response){
    deferred.resolve(response.data);
 });

  this.getcolors = function () {
    return deferred.promise;
};
 })

  angular
  .module('nApp')
   .controller('dataCtrl', ['$scope', 'dataService', '$location', function($scope,    dataService, $location) {

 var promise = dataService.getcolors();
  promise.then(function (data){
  $scope.colors = data.colors;
  });

Upvotes: 0

Views: 1257

Answers (1)

developer033
developer033

Reputation: 24874

Here's is a snippet working:

var app = angular.module('app', []);

app.controller('mainCtrl', function($scope) {
  $scope.colors = [  
     {  
        "color":"red",
        "value":"#f00",
        "message":"Simple message"
     },
     {  
        "color":"green",
        "value":"#0f0",
        "message":"Message with <strong>HTML</strong> tags"
     },
     {  
        "color":"blue",
        "value":"#00f",
        "message":"Am I going to work? I should not!"
     }
  ]
});
<!DOCTYPE html>
<html ng-app="app">

<head>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.7/angular.min.js"></script>
</head>
<body ng-controller="mainCtrl">
  <ul class="block-elements">
    <li ng-repeat="details in colors">
      <button ng-click="popupBtn()" ng-style="{ color: details.color }">Click Me</button>
    </li>
  </ul>
</body>
</html>

Upvotes: 1

Related Questions