我有ngrepeat显示:过滤器名称,旁边是所选值的计数器,按钮仅在计数器>时可见0
<li ng-repeat="filterType in filters" >
<span ng-bind="filterType.name"></span>
<span ng-bind="getSelectedValueCount(filterType.id)"> </span>
<button type="button" class="close" ng-if="getSelectedValueCount(filterType.id) > 0 ">Close</button>
</li>
目前我打电话给getSelectedValueCount(filterType.id)
两次。是否可以调用一次并在两个html标签之间共享价值?
我曾尝试过使用ng-init,但它并没有起作用 - 价值观并不令人耳目一新。
<li ng-repeat="filterType in filters" ng-init="myValue = getSelectedValueCount(filterType.id);" ng-model="myValue " >
<span ng-bind="filterType.name"></span>
<span ng-bind="myValue"> </span>
<button type="button" class="close" ng-if="myValue > 0 ">Close</button>
</li>
答案 0 :(得分:0)
只需在ng-bind指令中设置相应的变量而不是ng-init,因为ng-init只使用一次:
function MyCtrl($scope) {
var i = 1;
$scope.calc = function(id) {
return id - i;
}
$scope.filters =[
{name: "name1", id: 1},
{name: "name2", id: 2},
{name: "name3", id: 3},
{name: "name4", id: 4}
];
$scope.changeCalc = function() {
i++;
}
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app>
<div ng-controller="MyCtrl">
<li ng-repeat="filterType in filters" >
<span ng-bind="filterType.name"></span>
<span ng-bind="value = calc(filterType.id)"> </span>
<button type="button" class="close" ng-if="value > 0">Close</button>
</li>
<br />
<br />
<button type="button" class="close" ng-click="changeCalc()">Increment i</button>
<br />
Current calc(1): {{calc(1)}}
</div>
</div>