$ HTTP是没有定义 [英] $http is not defined
问题描述
我是新来的角JS和有得到以下错误,当我试图在项目中注入$ http服务。请参阅下面的code文件。
I am new to Angular JS and have getting below error when I have tried to inject $http service in the project. Please see the code file below.
正如你可以看到我已经创建了一个< NG-应用程序=的myapp>
和创造一个相同的控制器。正如在本教程中介绍我已经注册了View.js控制器,并试图加载data.json文件中的数据。然而,在运行程序时我正在为$ HTTP是没有定义的错误。
As you can see I have created a <ng-app="myapp">
and created a controller for the same. As described in the tutorial I have registered the controller in the View.js and tried to load 'data.json' file data. However, during running the program I am getting error as $http is not defined.
View.html
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
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:
data.json:
[
{
"rollNo" : "1",
"firstName" : "ABC",
"middleName" : "DEF"
"lastName" : "HIJ"
"className" : "First"
"schoolName" : "CRB"
}
]
推荐答案
与code没有问题,它的正常工作。
No problem with your code, it's working properly.
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
data.Json
您需要在每个键之间添加逗号:值
You need to add comma between each key:value
[
{
"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
});
这篇关于$ HTTP是没有定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!