如何将JSON对象作为函数参数存储在Angular中

How do you store a JSON object as a function parameter in Angular

本文关键字:存储 参数 Angular 函数 JSON 对象      更新时间:2023-09-26

我正在使用一个指令来使用AmCharts API填充图表。当前使用的函数列出了以JSON格式填充表单的数据,作为函数中的参数。我希望能够将其存储为一个变量,这样我就可以为JSON创建一个单独的文件。我知道您可能需要使用$http来获取json,但我不确定您将如何将其连接到指令。

var myapp = angular.module('tmn_portfolio', []);
myapp.directive('loadPortfolio',
 function () {
  return {
   restrict: 'E',
   replace:true,
   template: '<div id="chartdiv" style="min-width: 310px; height: 400px; margin: 0 auto"></div>',
   link: function (scope, element, attrs) {
        var chart = false;
        var initChart = function() {
          if (chart) chart.destroy();
          var config = scope.config || {};
           chart = AmCharts.makeChart("chartdiv", I WANT THIS TO BE A VARIABLE TO JSON FILE);
        };
        initChart();
 }//end watch           
  }
}) ;

scope: true更好的解决方案是将数据传递给属性中的指令。标记将如下所示:

<load-portfolio my-data="jsonData" ></load-portfolio>

该元素将被您的模板替换。指令中:

myapp.directive('loadPortfolio',
    function () {
        return {
            restrict: 'E',
            replace:true,
            scope: {
                myData: '='
            },
            template: '<div id="chartdiv" style="min-width: 310px; height: 400px; margin: 0 auto"></div>',
            link: function (scope, element, attrs) {
                var chart = false;
                var initChart = function() {
                    if (chart) chart.destroy();
                    var config = scope.config || {};
                    chart = AmCharts.makeChart("chartdiv", scope.myData);
                };
                initChart();
            }//end watch           
        }
    });

等号是指令作用域上的属性myData和控制器作用域上属性jsonData(角度术语中的"模型")之间的双向绑定。每当控制器中的数据发生变化时,指令中的数据也会发生变化,用户界面也会更新以反映这一点。

现在您只需要获取json数据,对吧?你是对的,你可能应该使用$http来完成这项工作,这将取决于你的具体实现,但重要的是,一旦你填充了jsonData,你的指令就会更新以反映这一点。我通常初始化将在控制器中异步填充的模型。一个非常简单的版本可能看起来像这样:

myapp.controller('myController', ['$scope', '$http', function($http, $scope) {
    $scope.jsonData = {};  // or '' - depending on whether you actually want the JSON string here.
    $http({
        url: '/data.json',
        method: 'GET'
    }).
    then(function(r) {
        $scope.jsonData = r.data;
    });
}]);

我认为,要正确地执行此操作,您应该研究路由和路由的resolve属性,该属性允许您在控制器加载之前检索数据,并将其作为参数传递给控制器,但这实际上取决于您。

更新:与其他答案一样,我建议使用工厂/服务来调用您的服务器或API,而不是像我的示例中那样直接在控制器中使用$http。只是尽量保持简单。如果组织良好,角度代码会更有趣。

您需要一个工厂或服务来首先请求JSON文件并将其存储为变量:

var app = angular.module('app', []);
app.config(['$httpProvider', function($httpProvider) {
$httpProvider.defaults.useXDomain = true;
delete $httpProvider.defaults.headers.common['X-Requested-With'];
}
]);

app.factory('data', function($http) { 
var data = {
    async: function() {
      // $http returns a promise, which has a then function, which also returns a promise
      var promise = $http.get('file.json').then(function (response) {
        // The then function here is an opportunity to modify the response
        console.log(response);
        // The return value gets picked up by the then in the controller.
        return response.data;
      });
      // Return the promise to the controller
      return promise;
    }
  };
  return data;
});
app.controller('MainCtrl', function( data,$scope) {
  // Call the async method and then do stuff with what is returned inside our own then function
  data.async().then(function(d) {
    $scope.jsonData = d; ;
  });
});