如何使用Angular的ng-style从JSON文件中获取数据

时间:2016-07-03 19:54:10

标签: javascript angularjs json

我正在尝试根据我的JSON文件中突出显示的属性设置元素样式。我目前正在使用ng-style来调用JSON对象中的属性

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

上面的示例似乎没有针对我的DOM上的节点定位样式

有没有人知道如何解决此问题。

{
 "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;
  });

1 个答案:

答案 0 :(得分:1)

这是一个代码片段:

&#13;
&#13;
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!"
     }
  ]
});
&#13;
<!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>
&#13;
&#13;
&#13;