簡體   English   中英

如何從json文件中讀取數據並在angularJS中作為字符串或對象返回?

[英]How to read the data from json file and return as string or object in angularJS?

personManagerInstance.getString(“ firstname”,'common','en')當前,我在ui中傳遞直接字符串,這確實影響了我,但我真正需要的是從json文件中讀取數據並以字符串形式返回。

personManagerInstance.getString(“ firstname”,'common','en')方法我需要從json文件中讀取數據並作為字符串或對象返回?

personManagerInstance.getString(“ lastname”,'registration','en')此方法基於參數,從不同位置讀取json並以字符串形式返回...

 var PersonManager = function () { return { $get: function ($http, person) { var mainInfo = $http({ method: "get", //"js/resources-locale_en_es.json" url: "js/resources-locale_en_es.json" }).success(function (data) { return data.title; }); return { getPersonFirstName: function () { return "as"; }, getPersonLastName: function () { return person.lastName; }, getString: function (labelid, moduleName, language) { //Here am getting the value id, moduleName, language based on the vaule I need to change the url path //(ie) js/resources-locale_en_es.json, js/registration/resources-locale_en_es.json var l = mainInfo.success(function (data) { person.firstName = data.title; }) return person.firstName; } }; } }; }; angular.module("mainModule", []) .value("person", { firstName: "", lastName: "" }) .provider("personManager", PersonManager) .controller("mainController", function ($scope, person, personManager) { person.firstName = "John"; person.lastName = "Doe"; $scope.personInstance = person; $scope.personManagerInstance = personManager; }); 
 <!DOCTYPE html> <html> <head> <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script> <script language="javascript" type="text/javascript" src="http://code.jquery.com/jquery-1.8.3.min.js"></script> <script src="script.js"></script> </head> <body ng-app="mainModule"> <div ng-controller="mainController"> <strong>First name:</strong> {{personManagerInstance.getPersonFirstName()}}<br /> <strong>Last name:</strong> {{personManagerInstance.getPersonLastName()}}<br /> <strong>Full name:</strong> {{personManagerInstance.getString("firstname",'common','en')}} {{personManagerInstance.getString("lastname",'registration','en')}}<br /> <br /> <label>Set the first name: <input type="text" ng-model="personInstance.firstName"/></label><br /> <label>Set the last name: <input type="text" ng-model="personInstance.lastName"/></label> </div> </body> </html> 

我看不到使用$http.get('file.json')任何麻煩, $http.get('file.json')可以使用angular.toJson(result)將JSON字符串轉換為對象。

http://plnkr.co/edit/4K9sy5aCP4NML0nnYgZ4

這是您的問題的解決方案

$http({
    method: "get",
    url: "link to your json file"
}).success(function (data) {
     callback(data);
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM