gpt4 book ai didi

javascript - Angular.js 范围变量未定义,ng-repeat 初始状态

转载 作者:行者123 更新时间:2023-12-02 17:57:39 27 4
gpt4 key购买 nike

嗨,我最近开始使用 Angular 和 Node,但立即遇到了问题。

我有一个简单的 Controller ,用于获取单个对象。一切正常,但我希望能够在 Controller 内初始化范围变量。我不知道如何做到这一点,我总是以“变量未定义”或 Controller 提供的空数据结束。

function FightCtrl($scope, $http, $location, $routeParams) {

var addNewCard = function(myDeck, data){
if (myDeck === undefined){
myDeck = []; //doing it this way, i no longer have exception with
//"undefined" myDeck variable, but no data is shown in webpage
}
myDeck.push({
myCard: data.card
});
return myDeck;
};

$scope.generateMyCard = function() {
$http.get('/api/fight/').
success(function(data) {
//simple, but works only for one fetched item (card)
//namely: i cannot use ng-repeat here :(
$scope.myDeck = {
myCard: data.card //"data.card" fetched by node, works like a charm
};

// this one is not working, and i would like to use something like this
//instead of solution presented 3 lines above
//$scope.myDeck = addNewCard($scope.myDeck, data);
});
};}

这里可能出了什么问题?我该如何修复它?

我的猜测是: $scope.myDeck 未正确初始化,但我不知道如何修复它。

顺便说一句。从html的 Angular 来看,一切都很好,我只是使用ng-repeat='myCard in myDeck'。当我添加连续元素但没有数据时,我可以在 gui 中观察到它们。

感谢任何帮助。

最佳答案

Initialise myDeck in the body of the controller like so:

function FightCtrl($scope, $http, $location, $routeParams) {

$scope.myDeck = [];

}

and you should be good to go.

You could also simplify the adding of card in the success handler to:

$scope.myDeck.push( { myCard : data.card });

关于javascript - Angular.js 范围变量未定义,ng-repeat 初始状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20862263/

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