使用Angular.JS将JSON导入HTML(错误)!

时间:2018-01-29 22:56:24

标签: javascript html angularjs json

我在使用Angular.JS将我的JSON数据传输到HTML时出现问题,我正在编写一个编程课程,这是我遇到的一个问题,作者似乎没有,有人可以帮忙吗?

我正确地链接了角度,我正确地添加了应用程序,它应该有用,有什么想法吗?

https://pastebin.com/K4HR23Tk - HTML

<html ng-app="myQuiz">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Test Your Knowledge: Saturn</title>
    <link rel="stylesheet" type="text/css" href="css/quiz.css">
</head>
<body>
<div id="myQuiz" ng-controller="QuizController">
<h1>Test Your Knowledge: <span>Saturn</span></h1>
<div class="progress"> {{totalQuestions}} </div>

https://pastebin.com/5emA4016 - JS

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

3 个答案:

答案 0 :(得分:1)

您的代码缺少结束方括号 public class TensorFlowImageClassifier implements Classifier { public static Classifier create( AssetManager assetManager, String modelFilename, String labelFilename, int inputSize, int imageMean, float imageStd, String inputName, String outputName) throws IOException { TensorFlowImageClassifier c = new TensorFlowImageClassifier(); c.inputName = inputName; c.outputName = outputName; // Read the label names into memory. // TODO(andrewharp): make this handle non-assets. String actualFilename = labelFilename.split("file:///android_asset/")[1]; Log.i(TAG, "Reading labels from: " + actualFilename); BufferedReader br = null; br = new BufferedReader(new InputStreamReader(assetManager.open(actualFilename))); String line; while ((line = br.readLine()) != null) { c.labels.add(line); } br.close(); c.inferenceInterface = new TensorFlowInferenceInterface(); if (c.inferenceInterface.initializeTensorFlow(assetManager, modelFilename) != 0) { throw new RuntimeException("TF initialization failed"); } // The shape of the output is [N, NUM_CLASSES], where N is the batch size. int numClasses = (int) c.inferenceInterface.graph().operation(outputName).output(0).shape().size(1); Log.i(TAG, "Read " + c.labels.size() + " labels, output layer size is " + numClasses); // Ideally, inputSize could have been retrieved from the shape of the input operation. Alas, // the placeholder node for input in the graphdef typically used does not specify a shape, so it // must be passed in as a parameter. c.inputSize = inputSize; c.imageMean = imageMean; c.imageStd = imageStd; // Pre-allocate buffers. c.outputNames = new String[]{outputName}; c.intValues = new int[inputSize * inputSize]; c.floatValues = new float[inputSize * inputSize * 3]; c.outputs = new float[numClasses]; return c; } @Override public List<Recognition> recognizeImage(final Bitmap bitmap) { // Log this method so that it can be analyzed with systrace. Trace.beginSection("recognizeImage"); Trace.beginSection("preprocessBitmap"); // Preprocess the image data from 0-255 int to normalized float based // on the provided parameters. bitmap.getPixels(intValues, 0, bitmap.getWidth(), 0, 0, bitmap.getWidth(), bitmap.getHeight()); for (int i = 0; i < intValues.length; ++i) { final int val = intValues[i]; floatValues[i * 3 + 0] = (((val >> 16) & 0xFF) - imageMean) / imageStd; floatValues[i * 3 + 1] = (((val >> 8) & 0xFF) - imageMean) / imageStd; floatValues[i * 3 + 2] = ((val & 0xFF) - imageMean) / imageStd; } Trace.endSection(); // Copy the input data into TensorFlow. Trace.beginSection("fillNodeFloat"); inferenceInterface.fillNodeFloat( inputName, new int[]{1, inputSize, inputSize, 3}, floatValues); Trace.endSection(); // Run the inference call. Trace.beginSection("runInference"); inferenceInterface.runInference(outputNames); Trace.endSection(); // Copy the output Tensor back into the output array. Trace.beginSection("readNodeFloat"); inferenceInterface.readNodeFloat(outputName, outputs); Trace.endSection(); // Find the best classifications. PriorityQueue<Recognition> pq = new PriorityQueue<Recognition>( 3, new Comparator<Recognition>() { @Override public int compare(Recognition lhs, Recognition rhs) { // Intentionally reversed to put high confidence at the head of the queue. return Float.compare(rhs.getConfidence(), lhs.getConfidence()); } }); for (int i = 0; i < outputs.length; ++i) { if (outputs[i] > THRESHOLD) { pq.add( new Recognition( "" + i, labels.size() > i ? labels.get(i) : "unknown", outputs[i], null)); } } final ArrayList<Recognition> recognitions = new ArrayList<Recognition>(); int recognitionsSize = Math.min(pq.size(), MAX_RESULTS); for (int i = 0; i < recognitionsSize; ++i) { recognitions.add(pq.poll()); } Trace.endSection(); // "recognizeImage" return recognitions; } @Override public void enableStatLogging(boolean debug) { inferenceInterface.enableStatLogging(debug); } @Override public String getStatString() { return inferenceInterface.getStatString(); } @Override public void close() { inferenceInterface.close(); } 。这是完成的代码:

&#13;
&#13;
]
&#13;
(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;
        }).catch(function(response){
            console.error(response && response.message || response);
            console.log("Using 2 dummy questions");
            $scope.myQuestions = ["dummy", "questions"];
            $scope.totalQuestions = $scope.myQuestions.length;
        });
    // below inserted the missing `]`.
    }]);
})();
&#13;
&#13;
&#13;

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <html ng-app="myQuiz"> <body ng-controller="QuizController"> <div>Total questions: {{totalQuestions}}</div> <div ng-repeat="question in myQuestions">{{question}}</div>之后[的开场'QuizController'从未被匹配的]关闭。

如果您使用合适的编辑器或linter来帮助突出显示或自动关闭每个块,则可以避免此错误。

来自某人的额外建议(我假设您是初学者,因为您提到了#34;粘贴&#34;在您的评论中,您确实声称了正在参加编程课程) - 如果你在这个简单的拼写错误中挣扎,那就意味着你走得太快而且不能停下来消化。 慢慢来,彻底阅读所有内容并尝试理解它。不要陷入复制和粘贴代码陷阱。这可能会花费你更多的时间来学习和编写好的代码。

快乐的编码!

答案 1 :(得分:0)

添加结束方括号}]);

你在这里打开数组[&#39; $ scope

答案 2 :(得分:0)

这不是直接答案,但包含有关如何避免OP遇到错误的提示。

始终从绝对最小代码开始,然后构建它,始终确保代码在增加复杂性时继续工作。每当它破裂时,显然你刚刚添加/更改了它。

在以下代码示例中,我删除了对IIFE的需求,并添加了"use strict"来激活我始终建议的Strict Mode。单击Run code snippet按钮查看代码:

&#13;
&#13;
angular.module('myQuiz',[]);
angular.module('myQuiz').controller('QuizController', function(){
  "use strict";
  console.log("QuizController");
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<html ng-app="myQuiz">
<div ng-controller="QuizController">
&#13;
&#13;
&#13;

使用数组语法注入依赖项(我认为在单独的行上格式化依赖项是个好主意):

&#13;
&#13;
angular.module('myQuiz',[]);
angular.module('myQuiz').controller('QuizController', [
    '$scope', '$http',
    function($scope, $http){ 
        "use strict";
        console.log("Injected $scope successfully?:", Boolean($scope));
        console.log("Injected $http successfully?:", Boolean($http));
    }
]);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<html ng-app="myQuiz">
<div ng-controller="QuizController">
&#13;
&#13;
&#13;

然后尝试访问外部数据。此示例引发错误。我将让您运行代码以了解原因:

&#13;
&#13;
angular.module('myQuiz',[]);
angular.module('myQuiz').controller('QuizController',[
    '$scope', '$http',
    function($scope, $http){ 
        "use strict";
        $http.get('quiz_data.json').then(function(quizData){
            console.log(quizData.data);
        }).catch(function(response){
            console.error("Unable to load quiz data");
            console.error(response && response.message || response);
        });
    }
]);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<html ng-app="myQuiz">
<div ng-controller="QuizController">
&#13;
&#13;
&#13;