从angularjs中的ngResource访问控制器内部的变量值

时间:2017-04-11 18:03:31

标签: angularjs ngresource

我在我的控制器内部调用一个API我想访问该对象的值我该怎么办?如果我使用数据绑定,我可以在对象中查看变量的值。

var app = angular.module("myApp",["ngResource"]);
app.factory("myAppFactory",function($resource){
  return{
    Test: $resource("https://jsonplaceholder.typicode.com/users/:id", {id:"@id"})
  }
});
app.controller("ctrl",function($scope,myAppFactory){
  var productDetailServer = myAppFactory.Test.get({ id: 1 }, function () {
    });
    var aux=productDetailServer;
    $scope.variable = productDetailServer;
    console.log(productDetailServer);
    console.log("the website\n");
    console.log(aux.website);
    console.log("how do you access variable inside the response?");
    /*
    How can I do something like this:

    var website =productDetailServer.website
    website should access the website within the productDetailServer object but 
    all I get is undefined, how do I assign the website propierty from the object to the variable?
    Thanks

    */
});

但是如何从控制器访问变量的值?感谢

我做了一个Plunker来更好地解释我的意思:

https://plnkr.co/edit/lSsxdbgc5eRXzuIV64ND?p=preview

1 个答案:

答案 0 :(得分:0)

它返回一个承诺,你应该使用它。

myAppFactory.Test.get({ id: 1 }).$promise.then(function (data) {
  $scope.variable = data;
});

Updated Plunker

您应该阅读How do I return the response from an asynchronous call?