我是Angular JS的新手,当我尝试在项目中注入$ http服务时,我遇到了以下错误。请参阅下面的代码文件。
正如您所看到的,我创建了一个<ng-app="myapp">
并为其创建了一个控制器。如教程中所述,我已在View.js中注册了控制器,并尝试加载'data.json'文件数据。但是,在运行程序期间,我收到错误,因为未定义$ http。
View.html
<!DOCTYPE html>
<html lang="en">
<head>
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.5/angular.min.js"></script>
<script src="js/View.js"></script>
</head>
<body ng-app="myapp">
<div ng-controller="Object">
<span ng-bind="o.rollNo"></span>
<span ng-bind="o.firstName"></span>
<span ng-bind="o.middleName"></span>
<span ng-bind="o.lastName"></span>
<span ng-bind="o.className"></span>
<span ng-bind="o.schoolName"></span>
</div>
</body>
</html>
View.js
var app=angular.module("myapp", []);
app.controller('Object',function($scope,$http) {
$http.get("data.json")
.success( function(response) {
$scope.o= response;
});
});
data.json:
[
{
"rollNo" : "1",
"firstName" : "ABC",
"middleName" : "DEF"
"lastName" : "HIJ"
"className" : "First"
"schoolName" : "CRB"
}
]
答案 0 :(得分:1)
您的代码没问题,它运行正常。
Since you have only 1 object, you need to get values based on index i.e o[0].rollNo
<body ng-app="myapp">
<div ng-controller="Object">
<span ng-bind="o[0].rollNo"></span>
<span ng-bind="o[0].firstName"></span>
<span ng-bind="o[0].middleName"></span>
<span ng-bind="o[0].lastName"></span>
<span ng-bind="o[0].className"></span>
<span ng-bind="o[0].schoolName"></span>
</div>
</body>
控制器
var app=angular.module("myapp", []);
app.controller('Object',function($scope,$http) {
$http.get('data.Json').
success(function(data, status, headers, config) {
alert("Success");
$scope.o = data;
}).
error(function(data, status, headers, config) {
alert("Error");
// log error
});
});
data.Json
您需要在每个键之间添加逗号:值
[
{
"rollNo" : "1",
"firstName" : "ABC",
"middleName" : "DEF",
"lastName" : "HIJ",
"className" : "First",
"schoolName" : "CRB"
}
]
根据您的项目结构,您的json文件路径(js / data.json)
$http.get('js/data.Json').
success(function(data, status, headers, config) {
alert("Success");
$scope.o = data;
}).
error(function(data, status, headers, config) {
alert("Error");
// log error
});
答案 1 :(得分:0)
由于答案中尚未提及此问题,因此仅在two comments中提及:
您可能需要移动
行<script src="js/View.js"></script>
到底部
<span ng-bind="o[0].schoolName"></span>
</div>
<script src="js/View.js"></script>
</body>
</html>
...另见@ Pratap关于JSON文件的答案。
答案 2 :(得分:-1)
试试这个:
var app=angular.module("myapp", []);
app.controller('Object', objectCtrl);
objectCtrl.$inject = ['$scope', '$http'];
function objectCtrl($scope, $http){
$http.get("data.json")
.success( function(response) {
$scope.o= response;
});
}