将angular.forEach与JSON一起使用

时间:2015-08-06 17:48:30

标签: javascript arrays json angularjs angularjs-ng-repeat

我尝试使用我的应用和控制器做的是制作一个"流程图样式"问答系统。我如何跟踪当前显示的问题和答案是使用$scope.ActiveQuestion和名为$scope.ActiveAnswers的数组。

我无法理解Angularjs的foreach方法。我曾经习惯在javascript中使用for循环,并且我尝试寻找可以解释foreach的东西,而不是基本for循环,我发现什么都没有。但这基本上是我试图用foreach做的事情。

对于当前answerIDs中的每个$scope.questions[$scope.ActiveQuestions].answerIDs,我想进入Answers并拉出包含该idAnswer的数组并将其推入名为{{1的新创建空数组}}。这将让我在模板中使用ng-repeat以及该问题所需的答案。

您可以在下面看到我的Json数据和我当前的控制器代码:

$scope.ActiveAnswers

问题:

app.controller('QuestionsCtrl', function($scope, $http) {

    // Pull Questions data
    $http.get("includes/getQuestions.php")
    .success(function(response) {
        $scope.Questions = response;
        $scope.ValidAnswers = $scope.Questions[$scope.ActiveQuestion].answerIDs.split(",");
    });
    // Pull Answers data
    $http.get("includes/getAnswers.php")
        .success(function(response) {
            $scope.Answers = response;
        });

    // Assign First Question
    if ($scope.ActiveQuestion == null) {
        $scope.ActiveQuestion = 1;
    };
    $scope.ActiveAnswers = [];
    angular.forEach($scope.Answers, function(idAnswers) {
        angular.forEach($scope.ValidAnswers, function(value) {
            if(value==idAnswers) {
                this.push(Answers)
            };
        });
    },$scope.ActiveAnswers);

});

我创建了一系列答案:

[
    [], {
        "idQuestion": "1",
        "answerIDs": "1",
        "text": "Don't know what to watch?"
    }, {
        "idQuestion": "2",
        "answerIDs": "2,3,4",
        "text": "Okay! First question: How new to anime are you?"
    }, {
        "idQuestion": "3",
        "answerIDs": "5,6,7,8,9,10",
        "text": "So your new! Awesome I've got a ton of anime for you, But lets get more specific. What type of anime interests you?"
    }, {
        "idQuestion": "4",
        "answerIDs": "11,12,13",
        "text": "Cool, Cool. What setting would you like?"
    }
]

奇怪的是,我没有收到任何错误,但它也没有填充[ [], { "idAnswer": "1", "nextQuestion": "2", "text": "Click here to get started", "animeID": null, "checkType": "0" }, { "idAnswer": "2", "nextQuestion": "3", "text": "...I've seen some GIFs", "animeID": null, "checkType": "0" }, { "idAnswer": "5", "nextQuestion": "4", "text": "Fantasy Action Adventure", "animeID": null, "checkType": "0" }, { "idAnswer": "11", "nextQuestion": null, "text": "Steampunk (magic, guns, early 1900s)", "animeID": "1", "checkType": "1" } ] 数组。任何帮助将不胜感激。

更新

应该提到的是,我最初将我的数据存储在MySQL数据库中,并使用PHP将数据编码到Json中来获取数据。

3 个答案:

答案 0 :(得分:1)

您可以使用承诺 $ q.defer()承诺经理来处理您的请求。

根据定义, $ http 返回承诺。

$ q.defer()获取2种方法:

  • resolve(value):通过给她最终值来解决我们的相关承诺

  • 拒绝(原因):解决了承诺错误。

<强>控制器

(function(){

function Controller($scope, Service, $q) {


  var defer = $q.defer();

  //create promise
  var promise1 = Service.get('includes/getQuestions.php"');

  var promise2 = Service.get('includes/getAnswers.php');

  //Create promise with $q
  var promiseAnswer = defer.promise;

  if ($scope.ActiveQuestion == null) {
      $scope.ActiveQuestion = 1;
  };

  //Retrieve data from promise1 & promise2
  $q.all([promise1, promise2]).then(function(response){
    //Get our question data
    $scope.Questions = response[0].data;
    //Get our answer data
    $scope.Answers = response[1].data;
    $scope.ValidAnswers = $scope.Questions[$scope.ActiveQuestion].answerIDs.split(",");
    $scope.ActiveAnswers = [];

    $scope.Answers.forEach(function(elm){
      $scope.ValidAnswers.forEach(function(value){
        //Access to elm.idAnswer and not just elm
        if (value === elm.idAnswer){
          $scope.ActiveAnswers.push(value);
        }
      });
    });

    //Resolve our data
    defer.resolve($scope.ActiveAnswers);

  });

  //When all the data are processed, retrieve our data
  promiseAnswer.then(function(data){
    console.log(data);
  });

}

angular
.module('app', [])
.controller('ctrl', Controller);

})();

然后,您应该使用服务进行请求处理:

<强>服务

(function(){

  function Service($http){

    function get(url){
      //Return a promise with specific url
      return $http.get(url);
    }

    var factory = {
      get: get
    };

    return factory;

  }

  angular
    .module('app')
    .factory('Service', Service);

})();

当您收到多个异步请求时,最好使用承诺 $ q.defer()

答案 1 :(得分:0)

我建议你做一个有问题的安排,叫做'#34;答案&#34;,把它放在一个数组和录音机里,比如:

[
 ["Question"],
   ["Answer"]
   {
    "idAnswer": "1",
    "nextQuestion": "2",
    "text": "Click here to get started",
    "animeID": null,
    "checkType": "0"
   },
]

不应该使你的循环失败

答案 2 :(得分:0)

在你的帮助下。我弄清楚如何避免修改我的数据库,最后让foreach循环工作。虽然它仍然被打破,但我在这个问题上遇到的问题从未得到解决。这是我更新的代码。

app.controller('QuestionsCtrl', function($scope, $http, $window) {

// Assign first question
if ($scope.ActiveQuestion == null) {
    $scope.ActiveQuestion = 1;
};
// Pull questions data
$http.get("includes/getQuestions.php").success(function(responseQuestions) {
    $scope.Questions = responseQuestions;
    $scope.ValidAnswers = $scope.Questions[$scope.ActiveQuestion].answerIDs.split(",");

    // Pull answers data
    $http.get("includes/getAnswers.php").success(function(responseAnswers) {
        $scope.Answers = responseAnswers;
        $scope.getActiveAnswers();
    });
});

$scope.getActiveAnswers = function() {
    $scope.ValidAnswers = $scope.Questions[$scope.ActiveQuestion].answerIDs.split(",");
    $scope.ActiveAnswers = [];
    angular.forEach($scope.ValidAnswers, function(answerid) {
        angular.forEach($scope.Answers, function(answer) {
            if (answer.idAnswer == answerid) {
                $scope.ActiveAnswers.push(answer);
            };
        });

    }, $scope.ActiveAnswers);
}

$scope.answerclick = function(nextQuestion) {
    $scope.ActiveQuestion = nextQuestion;
    $scope.getActiveAnswers();
};

});