【问题标题】:how to call a function under ng-repeat?如何在 ng-repeat 下调用函数?
【发布时间】:2017-06-20 15:02:29
【问题描述】:

我正在为我的项目使用 angularjs 1 和 node js。

在这里,我使用 ng-repeat 展示产品。我可以选择在社交网络中分享每个产品。我需要获取每个人的份额数,所以我需要调用一个函数来获得相同的数量。 我曾尝试调用函数 ng-init,但对于所有产品,它都会采用最后一个产品计数

这是我的示例代码

     <div ng-repeat="(key,popc) in product" class="courses-outer-div">       
          <div class="courses-text-div">
          <div class="course-title-div">
          {{popc.Title}}
          </div><br />
          <span class="ash-txt-sml">{{popc.ListFee|currency:"₹":0}}</span><br/>

<div class="common-left pad-top-10"><span class="blue-txt">Share</span><br />
<a target="_blank"  href="http://facebook.com/sharer.php?u=url&i=imagurl" target="_blank">
<img src="images/share-fb.png" width="24" height="23" alt="" /></a>
<div ng-init="getfbshare(popc.id)">{{fbcount}}</div>
</div>
</div></div>

Controller.js

$scope.getfbshare = function(id)
    {       
        $http.get('/api/fbcount'+id).then(function(response)
        {
            alert("f"+response.data.share.share_count)
            $scope.fbcount = response.data.share.share_count;           
        });
    };

alert 显示正确的值。

因为ng-repeat $scope.fbcount 取最后一个值。

请帮我找出解决办法

【问题讨论】:

    标签: angularjs angularjs-scope angularjs-ng-repeat


    【解决方案1】:

    您的 getfbshare 方法在作用域 ($scope.fbcount) 上设置了一个固定值,该值将被对该函数的任何后续调用覆盖。

    您可以传递整个popc 对象,而不是将popc.id 传递给您的函数,然后,您可以在响应中修改该对象,如下所示:

    $scope.getfbshare = function(popc)
    {       
        $http.get('/api/fbcount'+popc.id).then(function(response)
        {
            popc.fbcount = response.data.share.share_count;           
        });
    };
    

    那么,在你看来:

    <div ng-init="getfbshare(popc)">{{popc.fbcount}}</div>
    

    理想情况下,您应该在应用生命周期的不同部分调用该方法,而不是使用ng-init

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-22
      • 1970-01-01
      • 1970-01-01
      • 2016-05-20
      相关资源
      最近更新 更多