Previous questions haven't been satisfactory about this.
Most of AngularJS examples and tutorials online seem to always have tiny JSON arrays defined -inside- the js code...
So I'll reduce the code in a very basic sample:
(function(){
var app = angular.module('store', [ ]);
app.controller('StoreController', function(){
this.product = products;
});
var products = [
{name: "Linux Mint", origin: "Ireland"},
{name: "Ubuntu", origin: "Isle of Man"},
{name: "OpenSUSE", origin: "Germany"},
{name: "Fedora", origin: "USA"}
];
})();
I need to change the array "products" to load a json file -in the same folder-; no external tools or frameworks allowed and absolutely NO to setup servers and stuff as I have read in some previous answer. No changing code either, only the part after the "=", perhaps using $scope and $http.
How would you do that in a working way?
尝试这个:
(function(){ var app = angular.module('store',[]); app.controller('StoreController',['$http',function($http){ this.product=$http.get('file.json').success(function(resp){ return resp.data; }); }]); })();
Try this you just need to have your json setup in your directory and point the get request to it like any other get. Hope this helps. *This is meant as purely to mimic a request, although some of this could be written closely the same for a server request.
function ExampleController(exampleSerivce) {
var vm = this;
exampleSerivce.getPosts().then(function(response) {
vm.posts = response;
});
}
function exampleSerivce() {
var Posts = this,
URLS = {
FETCH: '/posts.json'
},
currentPostName,
allPosts;
Posts.getPosts = function() {
return $http.get(URLS.FETCH).then(function(response) {
return response.data
});
};
}
You could use FileReader
to read a local JSON
file. Working plunk: http://plnkr.co/edit/LtYOyeyxJncnmBGw5YRp?p=preview
app.controller("MainCtrl", ["$scope", function($scope) {
$scope.jsonString = "";
$scope.readFromFile = function() {
if(FileReader) {
var input = document.getElementById('myFile');
var file = input.files[0];
var fr = new FileReader();
fr.onload = function(e) {
$scope.jsonString = e.target.result;
$scope.$apply();
}
fr.readAsText(file);
} else {
window.alert('FileReader is not found, sorry');
}
}
}]);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.