Javascript angularjs:如何将函数返回值存储在一个变量中。基于ng重复

Javascript angularjs:如何将函数返回值存储在一个变量中。基于ng重复,javascript,angularjs,scope,return-value,ng-repeat,Javascript,Angularjs,Scope,Return Value,Ng Repeat,您好,我正在从ng repeat获取Intrested,我想调用另一个服务并将该数据动态存储在一个变量中,因为需要发送单独的api来获取图像 我的html是这样的 <div class="" ng-repeat="item in items" > <div ng-init="MyPic = getMyprofile(item.interestedTo)"> <img src="{{MyPic}}"> </div> </div&g

您好,我正在从ng repeat获取Intrested,我想调用另一个服务并将该数据动态存储在一个变量中,因为需要发送单独的api来获取图像

我的html是这样的

<div class="" ng-repeat="item in items" >
  <div ng-init="MyPic = getMyprofile(item.interestedTo)">
   <img src="{{MyPic}}">
  </div>
</div>
我的服务是这样的

    $scope.getMyprofile = function(IntrstdId){
    appServices.profile( IntrstdId,  function(response){
        $scope.meDetails = response.data;
    })
    return $scope.meDetails;

   }
service.profile= function(userId, callback) {
   path = serviceUrl + '/profile/'+ userId;
    $http({
        method: 'GET',
        url: path
        }).then(function(data) {
        callback(data)
    }, function(data) {});
}

但是它没有定义,这段代码中有任何问题。

我试图通过创建一些抽象存根来解决这个问题,这可能会对您有所帮助。如果问题仍然存在,请检查并让我知道

HTML

}

我认为问题在于这个函数。appService.profile是异步化方法,在完成它之前,函数返回
$scope.meDetails

我的建议是强化一些价值观,如下面所示,并看到结果。如果它正在工作,那么您必须相应地更改功能

$scope.meDetails ='some value';
return $scope.meDetails;

除了异步问题外,还有几个最佳实践问题

1.避免使用
ng init
,除非重建元素时要重新运行函数,例如
ng if
。如果使用
ng repeat
而不使用
track by
,则数据源中的任何更改都将重新触发子级中的所有
ng init

解决方案:在初始化控制器时运行它们,或者在填充
$scope.items
后立即运行它们

angular.forEach($scope.items, function(item) {
  appServices.profile(item).then(function(data){
    item.myPic = data;
  });
});

<div class="" ng-repeat="item in items" >
  <img src="{{item.myPic}}">
</div>

实际上我想传递一些id并存储响应。。。计数器=递增计数器(result.id);是的,您可以在服务中传递它,无论您想要什么,直到让我知道您在哪里找到问题我的问题是我想发送id,并将响应存储在变量中。配置文件(IntrstdId,函数(响应){},“IntrstdId”是从ng repeatHi获得的id,非常感谢,1.)对我来说是工作。。。2.$scope.getMyprofile=function(IntrstdId){return appServices.profile(IntrstdId);}我尝试了这个方法,但是在“$scope.getMyprofile”中没有得到任何返回值,总是显示空{}你不能用这个函数立即得到结果,你需要在你的控制器中使用它,方法是编写
$scope.getMyprofile(id)。然后(function(data){//您想在这里做什么})
$scope.getMyprofile = function(IntrstdId){
   appServices.profile( IntrstdId,  function(response){
      $scope.meDetails = response.data;
  })
return $scope.meDetails;
$scope.meDetails ='some value';
return $scope.meDetails;
angular.forEach($scope.items, function(item) {
  appServices.profile(item).then(function(data){
    item.myPic = data;
  });
});

<div class="" ng-repeat="item in items" >
  <img src="{{item.myPic}}">
</div>
// not needed anymore, just to showcase
$scope.getMyprofile = function(IntrstdId){
  return appServices.profile( IntrstdId );
}

// same goes with the service function
service.profile= function(userId) {
  path = serviceUrl + '/profile/'+ userId;
  return $http({
    method: 'GET',
    url: path
  }).then(function(response) {
    return response.data;
  });
}