gpt4 book ai didi

javascript - 如何使用 Angular JS 从外部范围访问数组值

转载 作者:行者123 更新时间:2023-12-03 00:43:52 25 4
gpt4 key购买 nike

好吧,我知道这是一个非常愚蠢的问题。在制作这条线之前我到处都查过了,但我完全无法弄清楚。这是我的代码。我的问题是,在将值从 getJSON 传递到 Angular Controller 之间,我的数组丢失了其值。执行我在这里尝试执行的操作的正确方法是什么?

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)
}

最佳答案

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

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

关于javascript - 如何使用 Angular JS 从外部范围访问数组值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53329438/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com