javascript - 从 $resource 对象 AngularJS 获取属性值

标签 javascript angularjs json rest

我是 AngularJS 的初学者,但我必须为我的项目修改小模块。 这是我的服务工厂:

services.factory('NewsService', function($resource) {

    var result = $resource('http://localhost:8090/boiler/1');
    return result;
});

我在这里使用它:

function IndexController($scope, NewsService) {

    var result = NewsService.get()

    $scope.xxx= result.day;
    $scope.www = result;

我不明白为什么我可以发送到 $scope 变量 result 并在 html 中将其用作 {{www.day}} 但我无法发送到变量 result.day 的 $scope 属性并将其用作 {{xxx}}

这是我来自服务器的 Json 响应

{
  "day" : "2016-10-06",
  "amountOfEnergy" : 40,
  "cost" : 120,
  "content" : [ ],
  "links" : [ {
    "rel" : "self",
    "href" : "http://localhost:8090/boiler/1"
  }, {
    "rel" : "bathroom",
    "href" : "http://localhost:8090/boiler/1"
  } ]
}

谁能给我解释一下?

最佳答案

$resource 返回 promise ,所以在 Controller 中使用 $promise.then

function IndexController($scope, NewsService) {
    NewsService.get()
       .$promise
       .then(function(response){
            console.log(response);
            var result = response;
            $scope.xxx= result.day;
            $scope.www = result;
       });
}

关于javascript - 从 $resource 对象 AngularJS 获取属性值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39703331/

相关文章:

javascript - 使用 ng-view 时可以保留变量作为 View 之间的引用吗?

javascript - 如何添加到 Angular 中现有 json 对象中的数组?

json - 通过 HTTP POST 编码二进制数据的最有效方法是什么

javascript - 当使用 id 而不是值单击单选按钮时,jQuery 显示 div

javascript - JQuery - 基于具有相同类的数据属性切换元素

javascript - JSON解析成HTML,对象如何映射到对应的HTML?

ios - NSString 的逗号分隔天数到 NSDate 计算与当前日期最接近的日期

javascript - 重命名对象中的字段

javascript - ng-focus 不适用于 <button> 标签

javascript - 执行 ajax 成功函数 - jQUERY