【问题标题】:Trying to import data from JSON file, and displaying in HTML尝试从 JSON 文件导入数据,并以 HTML 格式显示
【发布时间】:2017-01-06 10:53:52
【问题描述】:

这是我正在使用的脚本:

(function() {

    var app = angular.module("myQuiz", []);

    app.controller('QuizController', ['$scope', '$http', '$sce', function($scope, $http, $sce){

        $scope.score = 0;
        $scope.activeQuestion = -1;
        $scope.activeQuestionAnswered = 0;
        $scope.percentage = 0;

        $http.get('quiz_data.json').then(function(quizData){

            $scope.myQuestions = quizData.data;
            $scope.totalQuestions = $scope.myQuestions.length;

        });

    }])
})

在此之后,我尝试使用 {{totalQuestions}} 在我的 HTML 上显示“问题总数”,但它没有显示问题的数量,而是按原样显示 {{totalQuestions}}

【问题讨论】:

  • 您可能在控制台中遇到错误,请您提供一下吗?
  • 我正在使用 sublime 文本编辑器。当我在浏览器上运行我的 html 文件时,它只是按原样显示 {{totalQuestions}}。没有错误。
  • 您使用的是哪个浏览器,如果 chrome 直接读取文件可能会出错,否则与我们分享更多代码或创建http://plnkr.co 以复制问题
  • 错误出现在您的浏览器的控制台上,而不是在您的编辑器上...
  • 未捕获错误:[$injector:modulerr] errors.angularjs.org/1.6.1/$injector/…...(file%3A%2F%2F%2FF%3A%2FQuizApp%2FCh01%2F01_01%2Fangular.min.js%3A21%3A332)在 angular.min.js:6 在 angular.min.js:41 在 q (angular.min.js:7) 在 g (angular.min.js:40) 在 eb (angular.min.js:45) 在c (angular.min.js:21) 在 Mc (angular.min.js:21) 在 pe (angular.min.js:20) 在 angular.min.js:329 在 HTMLDocument.b (angular.min.js :37)

标签: html angularjs json


【解决方案1】:

你在代码中有这个:

(function() {
    var app = angular.module("myQuiz", []);
    // ..
})

但这永远不会真正执行函数,所以你的模块不会被定义。

只需在末尾添加()

(function() {
    var app = angular.module("myQuiz", []);
    // ..
}())

【讨论】:

  • 做到了。还是一样。
  • 你当然还必须在你的 index.html 中包含脚本:<head><script src="path/to/the/script.js"></script>
【解决方案2】:

尝试将<div id="myQuiz"> 重命名为不能与ng-app="myQuiz" 相同的名称,并在<div id="myQuizId" ng-controller = 'QuizController'> {{hereYourVariable}} </div> 中定义您的范围变量

【讨论】:

    【解决方案3】:

    在你的 index.html 文件中添加这些东西:

    1. ng-app = "myQuiz",
    2. ng-controller="QuizController" 如果需要,
    3. 添加对 Angular js cdn 或其脚本文件的引用
    4. 然后在 angular cdn/script 参考下方添加您的脚本文件参考。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-04
      • 1970-01-01
      • 2015-01-01
      • 2017-12-04
      相关资源
      最近更新 更多