我在“ ng-if ”中传递动态值时遇到问题。如果我传递一个静态值,那么它就起作用了,但是当我通过串联两个变量来传递动态值时,它就不起作用了。我尝试了以下代码:
<ul class="list cart">
<li class="cart_item"
ng-repeat="product in orderInfo.products track by product.product_id"
data-id="\{{product.product_id}}" id="items_list_{{product_id}}">
<button
ng-click="removeItem(product.product_id)"
// If I pass a static value like "removed_31460" then its working.
ng-if="removed_31460 == 'added'"
// If tried to pass a dynamic value like below I am getting error as token not accepted.
**ng-if="removed_+product.product_id == 'added'"**
data-product-id="{{item_id}}"
class="remove" data-id="\{{ product.product_id }}">
Remove
</button>
</li>
</ul>
注意:在我的app.js
文件中定义了“ removed_31460”。
这是可运行的代码:
function TodoCtrl($scope) {
$scope.products = [
{product_id:'123'},
{product_id:'234'},
];
let removed_id = '';
for (let i = 0; i < $scope.products.length; i++) {
removed_id = 'removed_'+ $scope.products[i].product_id;
$scope[removed_id] = 'added';
}
$scope.removeItem = function(product_id) {
alert('in ' + product_id);
};
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.0.3/angular.min.js"></script>
<div ng-app>
<div ng-controller="TodoCtrl">
<ul class="list cart">
<li class="cart_item" ng-repeat="product in products" data-id="\{{product.product_id}}" id="items_list_{{product_id}}">
<button
ng-click="removeItem(product.product_id)"
// If I pass a static value like "removed_31460" then its working.
ng-if="removed_23445 == 'added'"
// If tried to pass a dynamic value like below I am getting error as token not accepted.
**ng-if="removed_+product.product_id == 'added'"**
data-product-id="{{item_id}}"
class="remove" data-id="\{{ product.product_id }}">
Remove
</button>
</li>
</ul>
</div>
</div>
答案 0 :(得分:2)
使用:
ng-if="this['removed_' + product.product_id] == 'added'"
标识符this
可用于引用$scope
。
有关更多信息,请参见
可以更改代码以创建名为statusById
的哈希:
function TodoCtrl($scope) {
$scope.products = [
{product_id:'123'},
{product_id:'234'},
];
$scope.statusById = {};
$scope.products.forEach(p => $scope.statusById[p.product_id] = 'added');
$scope.removeItem = function(index) {
$scope.products.splice(index,1);
$scope.statusById[$scope.products[index].productId] = 'removed';
};
}
然后模板可以使用$index
:
<li ng-repeat="product in products" id="items_list_{{product_id}}">
<button ng-click="removeItem($index)"
ng-if="statusById[product.product_id] == 'added'"
>
Remove
</button>
</li>
有关更多信息,请参见
答案 1 :(得分:0)
尝试:True/False
。
如果您要动态添加ID,则绑定应位于上方,因此,如果产品ID为201,则表达式将被删除_201
答案 2 :(得分:0)
尝试使用此:
ng-if="removed_[product.product_id] == 'added'"
也许会帮到您。添加 JSFIDDLE 将很有帮助。
尝试以下可能性:
ng-if=" 'removed_' product.product_id == 'added' "
(已删除单引号)
ng-if=" 'removed_'[product.product_id] == 'added' "
(在单引号中已删除,在括号中将 $ scope变量)