简体   繁体   English

在AngularJS中正确传递函数中的值

[英]Passing value in function properly in AngularJS

I have the following function which takes variable description as parameter 我有以下以变量描述为参数的函数

$scope.relsingle = function(description) {
    console.log(description);
    var url = $scope.url+'/api/descrelation?limit=4&description='+description;
    $http.get(url).success(function(data) {
        console.log(data);
        $scope.apgresponse = data;
    })
};

I use the following approach to pass this value in the html page 我使用以下方法在html页面中传递此值

ng-init="relsingle(prodres[0].description)"

This value of prodres[0].description comes from here. prodres [0] .description的此值来自此处。 控制台输出

And value of prodres comes from here 产品价值就来自这里

$scope.prodat = function(id) {

    var uri = $scope.url+'/api/getproduct?productid='+id;
    console.log(uri);
    $http.get(uri).success(function(data) {
      console.log(id);
      console.log(data);
      $scope.prodres = data;
    })
  };

when i log the value of description in console in the relsingle function. 当我在relsingle函数的控制台中记录说明的值时。

console.log(description); console.log(description);

This gives me value undefined. 这给了我不确定的价值。

You can't do it like this with ngInit because it runs only once and when it happence variable prodres is not yet available because it comes from async call. 您无法使用ngInit做到这一点,因为它只能运行一次,并且在发生这种情况时变量prodres尚不可用,因为它来自异步调用。

What you can however do is to make ngInit execute only after the value for prodres has been resolved: 但是,您可以做的是仅在解决prodres的值后才使ngInit执行:

<div ng-if="prodres" ng-init="relsingle(prodres[0].description)">...</div>

Because ngIf has higher priority ngInit will execute only after ngIf . 由于ngIf具有更高的优先级,因此ngInit仅在ngIf之后执行。

好吧,因为这是因为该数组尚未在javascript中求值。使用回调函数并将该数组存储在$ scope范围内的变量中,然后可以在该函数中使用它

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM