如何在不编写JavaScript的情况下在AngularJS中包含JSON对象?

时间:2016-02-19 12:05:45

标签: angularjs json

我有一个带有此对象的JSON文件:

{"software":[
    {"name":"Eclipse", "version":"4.5"},
    {"name":"Sublime Text", "version":"3.0"},
    {"name":"ConEmu", "version":"1.5"}
]}

我想使用AngularJS内置指令获取值,我尝试使用ng-includeng-repeat,但不起作用:

<div ng-include="'software.JSON'" ng-repeat="sw in software">{{sw.name}} v{{sw.version}}</div>

2 个答案:

答案 0 :(得分:1)

演示应用

var MyApp = angular.module("MyApp",[]); // Inject app dependencies here

声明服务以获取JSON文件:

MyApp.factory("ConstantsService", ["$http", function($http){
    var ConstantsService = {};
    ConstantsService.getConstants = function(){
        return $http({
                    method: "GET",
                    url: "constants.json", //JSON file location
                    headers: {
                        'Content-Type': 'application/json'
                    }
                })
                .then(function(data){
                    return data;
                });
    }
    return ConstantsService;
}]);

ConstantsService 注入控制器并访问JSON内容:

MyApp.controller('FetchJsonController', ['$scope', 'ConstantsService', function($scope, ConstantsService){
    ConstantsService.getConstants().then(function(response){
           console.log(response.data.software); //Software object declared in JSON file
           $scope.software = response.data.software;
    });
}]);

最后定义模板

<div ng-controller="FetchJsonController">
     <div ng-repeat="sw in software">{{sw.name}} v{{sw.version}}</div>
</div>

答案 1 :(得分:0)

ng-include指令不是为此目的而制作的。

  

ngInclude

     
      模块ng中的
  • 指令   获取,编译并包含外部HTML片段。
  •   

尝试在控制器中使用$ http.get实现它。但如果你真的需要一个指令......

http://jsfiddle.net/U3pVM/22528/

JS

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

app.controller("IncludeJsonController", IncludeJsonController);

app.directive("includeJson",[function() { 
return {
    template: "<div ng-repeat=\"sw in vm.software\"><p>{{ sw.name }} v{{ sw.version}}</p></div>",
  controller: "IncludeJsonController",
  restrict: "E",
  link: function(scope, element, attr, ctrl) {
        scope.vm = {};
      scope.vm.filename = attr.filename;
      scope.vm.software = ctrl.getSoftwares();
  }
}}]);

IncludeJsonController.$inject = ['$scope', '$http'];

function IncludeJsonController($scope, $http) {
    var self = this;

    self.getSoftwares = getSoftwares;

    function getSoftwares() {
    //in your case, use $http.get('path/to' + $scope.vm.filename);
      return [
        {"name":"Eclipse", "version":"4.5"},
        {"name":"Sublime Text", "version":"3.0"},
        {"name":"ConEmu", "version":"1.5"}
      ];
    }

}
}());

HTML

<div ng-app="app">
   <include-json filename="software.json"></include-json>
</div>