Json AngularJS-访问范围中的元素
我已经完成了一项服务,从服务器获取一个json文件,其中包含我的webapp标签的翻译值。似乎效果不错:Json AngularJS-访问范围中的元素,json,angularjs,scope,share,Json,Angularjs,Scope,Share,我已经完成了一项服务,从服务器获取一个json文件,其中包含我的webapp标签的翻译值。似乎效果不错: mobilityApp.service('serveiTraduccions', function($resource) { this.getTranslation = function($scope) { var languageFilePath = 'traduccions/traduccio_en.json'; $resource(langua
mobilityApp.service('serveiTraduccions', function($resource) {
this.getTranslation = function($scope) {
var languageFilePath = 'traduccions/traduccio_en.json';
$resource(languageFilePath).get(function (data) {
$scope.translation = data;
});
};
});
我试图做的是从我的控制者那里获得“$scope.translation”,我尝试了所有的方法,但没有任何效果。该对象保存在my$scope中,如您所见:
如何获取“registroBtnRegistro”、“registroErrorRegistro”等的值
提前谢谢
我试过:
console.log($scope.translation)代码>->未定义
console.log($scope['translation'])代码>->未定义
console.log($scope.translation.registroBtnRegistro)代码>->类型错误: 无法读取未定义的属性'registroBtnRegistro' console.log($scope.translation['registroBtnRegistro']);->类型错误: 无法读取未定义的属性'registroBtnRegistro'
mobilityApp.service('serveiTraduccions', function($resource, $rootScope) {
this.getTranslation = function() {
var languageFilePath = 'traduccions/traduccio_en.json';
$resource(languageFilePath).get(function (data) {
$rootScope.translation = data;
});
};
});
这是一个盲目的尝试,因为你原来的帖子缺少基本信息,比如控制器的呼叫。 我们可以改进它,直到我们使它工作 首先,您应该从方法中返回一些内容:
mobilityApp.service('serveiTraduccions', function($resource) {
this.getTranslation = function() {
var languageFilePath = 'traduccions/traduccio_en.json';
return $resource(languageFilePath);
};
});
您使用的是$resource
,但也可以使用basic$http.get()
。至少在我看来它不像restful api。
在任何情况下,由于它是一个异步请求,因此它不会返回已翻译字符串的列表,而是一个资源“类”,允许使用get
、delete
或更一般的query()
:
从文档中:默认方法为
{'get':{method:'get'},
'save':{method:'POST'},
'query':{method:'GET',isArray:true},
'remove':{method:'DELETE'},
'delete':{method:'delete'}}
旁注:在服务中注入$scope
对我来说没有多大意义:服务用于封装公共逻辑组件。但是,可以将范围实例作为参数传递
然后,使用它的控制器应该注入服务,并在结果到达时使用回调来获取结果(异步操作!):
我们有一个有效的例子。SO中的其他问题也已经解决了这一问题,如您能否将尝试添加到问题中?也许你想在承诺解决之前访问它们?标记是什么样子的?保持不变,它输出未定义的值。您如何尝试在html中显示这些值?我看到你的翻译对象是一个承诺,而不是你的服务器返回的数据。好的,像这样在我的HTML中输出值是有效的{{translation.registroPlaceholderRegistro}}我尝试使用console.log来检查值是否正确,但是如果我可以在HTML中输出它,那就好了,谢谢!!这是因为$resource.get函数是一个异步函数,您试图在resource.get返回之前调用console.log。尝试这样调用console.log:$timeout(function(){console.log($scope.translation.RegistrPlaceHolderRegistro);},0);不要忘了在控制器中注入$timeout。
$timeout
可能适合快速调试,但对于真正的代码来说,这是一个糟糕的解决方案,应该正确使用承诺
TraduccioCtrl ... {
$scope.translation = {}; // avoid undefined when the view just loads
ServeiTraduccions.getTranslation.query(function (response) {
$scope.translation = response; // and angular's two-way data binding will probably do the rest
});
}