2017-06-20 258 views
1

我想訪問另一個對象內部的對象,但是每當我對其進行控制時,它都會顯示'undefined'。 例另一個對象的訪問對象

$scope.instrumento = new Instrumento(); 

$scope.empresaInstrumento = EmpresaInstrumento.get({id:$routeParams.id}, function (instrumento) { 
    $scope.instrumento = instrumento.instrumento; 
    console.log($scope.instrumento); 

}); 
console.log($scope.instrumento); 

我怎樣才能得到這個對象「INSTRUMENTO」出來的「empresaInstrumento」沒有失去他的參考?

(在得到方法從API信息)

+0

做您的控制檯INSTRUMENTO,並檢查是否有INSTRUMENTO? –

+0

是的,它有。 「empresaInstrumento」顯示對象「empresa」和「instrumento」。 當我控制檯empresaInstrumento.instrumento不斷顯示'未定義',但裏面的功能,它顯示正確的儀器 –

+0

什麼版本的角?您的服務EmpresaInstrumento.get使用$ http還是自定義承諾? – gyc

回答

0

這是因爲該功能empresaInstrumento沒有一個名爲instrumento屬性。

這樣說,更好的方法是做以下工作;

$scope.instrumento = new Instrumento(); 

$scope.empresaInstrumento = { 
// create an instrumento property 
    instrumento: function() { 
     var toReturn = {}; 
     EmpresaInstrumento.get({id:$routeParams.id}, function (instrumento) { 
      toReturn = instrumento.instrumento; 
     }); 

     return toReturn; 
    } 
} 
console.log($scope.empresaInstrumento.instrumento()); 
1

在你的代碼沒有function$scope.empresaInstrumento內運行,你必須使它爲function,然後從控制器或視圖稱呼其爲ng-init,看樣品

app.controller("ctrl", ["$scope", "EmpresaInstrumento", "$routeParams", function ($scope, empresaInstrumento, routeParams) { 
    $scope.instrumento = {}; 

    $scope.empresaInstrumento = function() { 
     empresaInstrumento.get({ id: routeParams.id }, function (instrumento) { 
      $scope.instrumento = instrumento.instrumento; 
      console.log($scope.instrumento); 
     }); 
    } 

    $scope.empresaInstrumento(); //or in ng-init="empresaInstrumento()" 

    console.log($scope.instrumento); 
}]); 
1

我猜你沒有看到你的html頁面正在更新範圍值,並且你添加了console.logs來測試值是否被正確設置。

你有2個問題:API調用返回任何數據之前

1-第二的console.log將被執行。這就是爲什麼你沒有定義。 (第一個日誌應該顯示正確的值,因爲它在promise框內

2-取決於EmpresaInstrumento.get的編碼方式,它可能是您需要使用$ scope更新範圍值的情況。適用於();

$scope.instrumento = new Instrumento(); 

$scope.empresaInstrumento = EmpresaInstrumento.get({id:$routeParams.id}, function (instrumento) { 
    $scope.instrumento = instrumento.instrumento; 
    console.log($scope.instrumento); 
    $scope.$apply(); // update the scope and your view 
}); 
console.log($scope.instrumento); // still undefined here 

但是,如果第一的console.log顯示不確定的,你有你的服務有問題,我們需要看看它是如何編碼調試它

+0

謝謝!這似乎更令人愉快,我做的方式。 我會稍後再嘗試重構代碼 –

0

爲馬赫說有,我。使用本地變量來捕獲響應,然後我能夠保存該信息調用回調中的命名函數發送到$範圍變量使用局部變量在函數中創建。

是這樣的:

$scope.empresaInstrumento = function() { 
 
     empresaInstrumento.get({ id: routeParams.id }, function (instrumento) { 
 
      $scope.instrumento = instrumento.instrumento; 
 
      $scope.loadInstrumento($scope.instrumento); 
 
     }); 
 
    } 
 
    
 
    
 
    $scope.loadInstrument = function loadInstrument(element) { 
 
     $scope.instrumento = element; 
 
    }

所以,當我要求的信息,它正確地顯示在HTML