简体   繁体   中英

Trigger ng-click inside ng-repeat when ng-repeat item.length=1

I want to trigger automatic loadProduct function when products.length==1

Bellow my angular code.

<div class="prodItem prodItem-nos-{{products.length}} prodItem-item-number-{{$index}}"
    ng-repeat="product in products track by $index"
    ng-click="loadProduct(product.id)"
    uib-tooltip="{{ product.name }}">

    <div class="prodMeta">    
        <div class="prodName" ng-bind="product.name"></div>
        <div class="prodDescr" ng-bind="product.description"></div>
    </div>  
    <div class="prodBuyNow">
        <button ng-click="loadProduct(product.id)">Choose</button>
    </div>
</div> 

If you want to trigger function when item in scope changes you can use scope.$watch()

for example :

scope.$watch('products',function(oldValue,newValue){
            if(newValue.length === 1){
               executeFunction();
            }
    });

See : https://docs.angularjs.org/api/ng/type/ $rootScope.Scope

ng-click="if(products.length === 1){ loadProduct(product.id); }"

I don't like too much conditions inside ng-click. Being products a scope variable, you can just add this logic inside your loadProduct function, adding a condition at the beginning like

if($scope.products.length === 1)

and then execute your code.

If, you want to call loadProduct() is only one product is there call it in api which fetched the products

Eg:

$http.get("/api/products")
    .then(function(response) {
        $scope.products = response.data;
        if($scope.products.length == 1)
        {
            $scope.loadProduct($scope.products[0].id)
        }
});

you can use ng-init function and check your prodt list in the function

<div ng-repeat="product in products track by $index" ng-init="yourFunctionName()">
<div class="prodMeta">    
 <div class="prodName" ng-bind="product.name"></div>
 <div class="prodDescr" ng-bind="product.description"></div>
 </div>  
   <div class="prodBuyNow"><button ng-click="loadProduct(product.id)">Choose</button></div>
</div> 
</div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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