【问题标题】:How to define angularjs variables inside script如何在脚本中定义angularjs变量
【发布时间】:2015-11-21 10:03:04
【问题描述】:

我正在使用简单的get方法

var self= this;
self.items = [];
var fetchGraphs = function() {
        return $http.get('/api/graph').then(
                    function(response) {
                            self.items = response.data;
                            alert(self.items);
                    }, function(errResponse) {
                            console.error('Error while fetching notes');
                    });
         };` 

获取以下 JSON 数据。

{
 "Msg": "Running",
 "excMsg": null,
 "array1": {
        "key1": 32,
        "key2": 10,
        "key3": 24
    },

 "array2": {
        "key4": 42,
        "key5": 20,
        "key5": 22
    }}

现在我必须为array1 和array2 绘制图形。为此,我必须在脚本中声明 get 方法中的值。但它给了我错误

“无法读取 key1 属性。”

谁能告诉我如何在另一个脚本文件中声明从 JSON 获得的数组变量

【问题讨论】:

  • 响应成功时可以调用带有json数据的函数

标签: javascript json angularjs angularjs-directive angularjs-scope


【解决方案1】:

您不能直接“声明”变量。您必须使用方法或订阅事件。简单的解决方案 scope.emit 等。请参见此处: Working with $scope.$emit and $scope.$on 例如,如果您想使用 fetchGraphs (您的方法)。

fetchGraphs().then(function(result) {
   // do something with result array 
});

编辑:

如果您在这里发布更多代码,人们可以帮助您提高效率。

【讨论】:

    【解决方案2】:

    您必须使用 fetchGraph 中的 then 方法,否则从 $http 的成功方法中返回数据。

    我的建议,你可以关注self.items。因此,每当它发生变化时,您都可以重新绘制图表。

    $scope.$watch(
        "self.items",
         function () {
              //re-draw your graph
              $scope.$apply(); // not needed always, just a precaution
          }
    );
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-06-08
      • 1970-01-01
      • 1970-01-01
      • 2018-03-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多