我想在products.length==1
时触发自动加载产品函数
低吼我的角度代码。
<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>
如果你想在
范围内的项目发生变化时触发函数,你可以使用scope.$watch((
例如:
scope.$watch('products',function(oldValue,newValue){
if(newValue.length === 1){
executeFunction();
}
});
看:https://docs.angularjs.org/api/ng/type/$rootScope.Scope
ng-click="if(products.length === 1){ loadProduct(product.id); }"
我不喜欢ng-click中有太多条件。由于产品是一个范围变量,你可以在 loadProduct 函数中添加这个逻辑,在开头添加一个条件,比如
if($scope.products.length === 1)
然后执行您的代码。
如果你想调用loadProduct()
只有一个产品,在获取产品的 api 中调用它
例如:
$http.get("/api/products")
.then(function(response) {
$scope.products = response.data;
if($scope.products.length == 1)
{
$scope.loadProduct($scope.products[0].id)
}
});
你可以
使用ng-init函数并在函数中检查您的产品列表
<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>