问题描述
我正在创建一个个人网站,我可以继续更新内容,而无需操纵 HTML
。我试图通过简单地加载和更新 JSON
文件来实现这一目的。但是现在,我在将 JSON
数据加载到范围
变量时遇到了问题。
I'm creating a personal website where I can keep updating content without having to manipulate the HTML
. I'm trying to achieve this by simply loading and updating a JSON
file. But right now, I'm having trouble loading JSON
data onto a scope
variable.
HTML
<!doctype html>
<html>
<head>
<script src="angular.min.js" type="text/javascript"></script>
<script src="maincontroller.js" type="text/javascript"></script>
</head>
<body>
<div ng-app="mainApp" ng-controller="mainController">
<div id="content">
<div ng-repeat="content in contents">
<h2>{{content.heading}}</h2>
<p>{{content.description}}</h2>
</div>
</div>
</div>
</body>
</html>
maincontroller.js
var myapp = angular.module('mainApp', []);
myapp.controller('mainController',function($scope,$http){
$scope.contents = null;
$http.get('mainContent.json')
.success(function(data) {
$scope.contents=data;
})
.error(function(data,status,error,config){
$scope.contents = [{heading:"Error",description:"Could not load json data"}];
});
//$scope.contents = [{heading:"Content heading", description:"The actual content"}];
//Just a placeholder. All web content will be in this format
});
这是 JSON
文件的样子
[
{"heading":"MyHeading","description":"myDescription"},
]
我实际上尝试遵循给定的解决方案,但它没有加载 JSON
文件存储在同一文件夹中。我得到的输出来自错误处理函数,它说错误:无法加载JSON数据
如上所述。
I actually tried following the solution given here, but it's not loading the JSON
file stored in the same folder. The output I get is from the error handling function which is saying Error: Cannot load JSON data
as mentioned.
我做错了什么?
编辑:我在,它工作正常。它只是不能在我的本地机器上工作。
I put the same code on plunker and it works fine. It's just not working on my local machine.
推荐答案
修改你的方法使用它和检查输出。
Modified Your Method Use this and Check output.
var myapp=angular.module('mainApp',[]);
myapp.controller('mainController',function($scope,$http){
$scope.content = null;
$http.get('urlpath'}).
success(function(data, status, headers, config) {
$scope.contents=data;
}).error(function(data, status, headers, config) {
});
});
或我看到的另一个良好做法
or Another Good Practice I see
使用工厂服务方法: -
Use Factory Service Method:-
angular.module('mainApp').factory('Myservice', function($http){
return {
getdata: function(){
return $http.get('url'); // You Have to give Correct Url either Local path or api etc
}
};
});
向控制器注入上述服务
控制器: -
angular.module('mainApp',[]).controller('mainController',function($scope,Myservice){
$scope.content = null;
Myservice.getdata().success(function (data){
alert('Success');
$scope.content=data[0]; // as per emilySmitley Answer which is Working Good
});
});
如果您有任何疑问,请告诉我。祝你好运
Let Me Know if You have any Questions . Good Luck
这篇关于AngularJS:如何将JSON数据加载到范围变量上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!