我在localhost:5000上设置了一个服务器,该服务器的JSON字符串包含“ Hello world”
我希望AngularJS应用程序获取此数据并显示。
这是我所拥有的。
这是脚本getJSON.js
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
$http({
method : "GET",
url : "localhost:5000"
}).then(function mySuccess(response) {
$scope.myWelcome = response.data;
}, function myError(response) {
$scope.myWelcome = response.statusText;
});
});
这就是我在html中的称呼方式
<div ng-app="myApp" ng-controller="myCtrl">
<p>Today's welcome message is:</p>
<h1>{{myWelcome}}</h1>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
$http.get("localhost:5000")
.then(function(response) {
$scope.myWelcome = response.data;
});
});
</script>
现在“ myWelcome”应该是“ Hello world”,但是在运行代码时它仅显示myWelcome。
后端完全正常工作!我已经使用常规Angular完成了此操作,但不幸的是,它需要它与AngularJS一起使用。
有什么建议吗?
答案 0 :(得分:1)
这不是一个完整的答案我明白您正在尝试做什么。好像您没有调用正确的控制器,并且您的值永远不会更新。将您的应用程序定义移到脚本标记中,并删除那里的控制器
//index.html
<script>
var app = angular.module('myApp', []);
</script>
// myCtrl.js
app.controller('myCtrl', function($scope, $http) {
$scope.myWelcome = 'test';
$http({
method : "GET",
url : "localhost:5000"
}).then(response) {
$scope.myWelcome = response.data;
}, catch(error) {
$scope.myWelcome = error;
});
});
接下来,检查您的网络标签,查看请求是否实际执行。如果不是,则表明您的控制器未正确连接到应用程序。此时,您应该能够设置断点,并查看触发什么和不触发什么。
编辑:另外,请确保在第一个脚本标签触发后将js文件加载到视图中。否则,将不会定义“ app”。