【问题标题】:How to access Array value from outside scope with Angular JS如何使用 Angular JS 从外部范围访问数组值
【发布时间】:2019-04-19 03:29:02
【问题描述】:

好的,我知道这是一个非常愚蠢的问题。在制作这个线程之前,我到处寻找,我完全无法弄清楚。这是我的代码。我的问题是在将值从 getJSON 传递到角度控制器之间,我的数组丢失了它的值。什么是我在这里尝试做的正确方法?

function getJSON(json) {
    data = [];
    $.each(json, function (index, value) {
        data.push(value);
    });
    console.log(data); // Accurately logs array data
    return data;
}
function passValue() {
    return getJSON();
}
app.controller('ExampleController', function($scope) {
    x = passValue()
    $scope.title = x[0]; // Throws error
    console.log(x); // Only returns an empty array
}

这是我在我的 html 文件中的一个脚本。 100% 有效。

$(document).ready(function() {
    $.getJSON("{{ url_for('static', filename='movies.json') }}?id={{ movie_id }}", function(json) {
         getJSON(json);
});

例如,这是可行的。

function getJSON(json) {
    data = [];
    $.each(json, function (index, value) {
        data.push(value);
    });
    console.log(data) // Acurrately logs array data
    document.getElementById('exampleDiv').innerHTML = data[0] // Accurately appends array data (0 being title)
}

【问题讨论】:

  • 这段代码看起来简化了,是吗?我怀疑缺少一些关键行,例如 fetch 或类似的东西
  • 我的 getJSON 方法没有简化。它适用于获取我的 json 数据。它是从另一个脚本调用的方法。我可以用它来正常地将 json 值放入 html 中,但我正在尝试弄清楚如何使用 HTML 来完成它。我会将其他代码放入我的主帖中。
  • 嗯,有趣。我很惊讶,如果x 是一个空数组,那么$scope.title = x[0]; 会引发错误,因为应该 只需将undefined 分配给$scope.title。可能是我不熟悉的棱角分明的东西
  • 是的,我对 angular 也很不熟悉,我敢肯定这个问题有一个简单的解决方案,我只是想不出一个。老实说,我可能只是愚蠢!
  • 您在 passValue 函数中调用 getJSON() 时没有参数。正如 getJSON 函数定义所期望的那样,这似乎不正确。

标签: javascript jquery angularjs json


【解决方案1】:

我找到了解决我的问题的解决方案。如果有人有类似的问题,我希望这对你也有帮助。

function getJSON(json) {
    data = [];
    $.each(json, function (index, value) {
        data.push(value);
    });
    console.log(data)
    update(data)
}

function update(data) {
    var $scope = angular.element(document.querySelector('#movie')).scope()
    $scope.$apply(function(){
        $scope.title = data[0];
    });
}

app.controller('MovieController', function($scope) {
});

【讨论】:

    【解决方案2】:

    您可以使用window 在 Angular 和任何组件之间存储和访问数据。 Angular 也有一个名为 $window 的包装器来访问它。

    在javascript中:

    function foo(value){
        window.data = value;
    }
    

    角度:

    app.controller('ctrl', ['$scope', '$window', function($scope, $window) {
    
      $scope.getData= function() {
        //using $window
        alert($window.data);
        //Or 
        alert(window.data);
      };
    }]);
    

    【讨论】:

      猜你喜欢
      • 2016-06-23
      • 2016-06-24
      • 2018-11-09
      • 1970-01-01
      • 2013-03-03
      • 1970-01-01
      • 1970-01-01
      • 2016-05-30
      • 1970-01-01
      相关资源
      最近更新 更多