AngularJS的JSON对象可以在视图中访问,但不能在控制器中访问
AngularJS JSON object accessible in view, but not accessible in controller
我有一个简单的服务,它获得一些openWeather JSON。然后将服务注入到控制器中。在控制器中,我不能访问JSON中的对象,但是,当绑定到时,我可以毫无问题地访问对象数据。我是JS和Angular的新手,我做错了什么?
mcmdApp.service('areaWeatherService', ['$resource', function($resource){
this.weatherAPI = $resource("http://api.openweathermap.org/data/2.5/weather", {get: {method: "JSON"}});
this.weatherResult = this.weatherAPI.get({q: "London,uk"});
}]);
控制器mcmdApp.controller('SingleElementController',['$scope', 'areaWeatherService',function($scope, areaWeatherService){
$scope.weatherResult = areaWeatherService.weatherResult;
console.log($scope.weatherResult); //<-- Shows Object in Console
console.log($scope.weatherResult.wind); //<-- PROBLEM: Shows Undefined
console.log($scope.weatherResult.wind.speed); //<-- PROBLEM: Shows cannot read property 'speed' of Undefined
}]);
<<p> 视图/strong> <div class="single-element-widget text-center">
<h2>{{weatherResult.wind.speed}} mph</h2><!-- NO PROBLEM, displays correctly -->
<small>{{weatherResult.wind.deg}} degrees</small><!-- NO PROBLEM, displays correctly -->
</div>
我试图从控制器或服务访问对象和属性。
console.log($scope.weatherResult);
结果
e {$promise: d, $resolved: false}$promise: d$resolved: truebase: "cmc stations"clouds: Objectcod: 200coord: Objectdt: 1441164423id: 2643743main: Objectname: "London"sys: Objectweather: Array[1]wind: Object__proto__: e
您正在使用$http
承诺。日志语句在从服务器返回数据之前触发。试试这个:
$scope.weatherResult = areaWeatherService.weatherResult.$promise.then(function(resp){
console.log(resp);
console.log(areaWeatherService.weatherResult.wind);
});
.then()
将等待您的承诺被解决,然后执行结果代码
相关文章:
- JS可以在Chrome中工作,但不能在Firefox中工作
- WebRTC视频聊天可以在FF中使用,但不能在Chrome中使用
- jQuery Datepicker可以在Safari中工作,但不能在FF或Chrome中工作
- 三角库可以与firefox一起使用,但不能在Chrome中使用
- Highcharts可以从服务器加载数据,但不能更新
- 刷新GoogleMaps tile服务器可以使用JavaScript,但不能使用GWT
- node.js可以识别字符模式,但不能识别数字模式
- 如何在元素中处理鼠标事件,但不能在其子元素上处理
- Json到CSV下载,可以在chrome中工作,但不能在IE浏览器中工作
- jQuery$.post可以在chrome、safari中工作,但不能在FF中工作(声明成功回调函数未定义)
- 为什么我可以在javascript中访问asp:TextBox,但不能访问asp:Label
- 扩展了类,但不能访问子类的函数
- IAM允许访问一个dynamoDB方法,但不能访问另一个使用javascript到AWS的方法
- 解析AJAX HTML响应:我可以找到元素,但不能访问它们的innerHTML或值
- Angular Ui-Router |从控制器访问视图中的作用域变量,但不能正常工作
- 为什么我可以访问iFrame,但不能访问它的内容?
- 返回JSON对象,但不能通过$.ajax()访问
- AngularJS的JSON对象可以在视图中访问,但不能在控制器中访问
- 可以访问对象的属性,但不能访问函数
- 在内容脚本中定义的脚本,但不能在弹出(Chrome扩展)访问