2017-06-20 187 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