gpt4 book ai didi

javascript - 如何更新 ng-repeat 中使用的变量的所有副本

转载 作者:行者123 更新时间:2023-11-29 15:35:21 34 4
gpt4 key购买 nike

我需要增加相应的值,点击+按钮,
但与此同时,在点击任何 reset 按钮时,我需要将所有值重置为 100。

目前,我可以通过点击 + 按钮来增加相应的值,但是在点击 reset 按钮时,只有没有增加的值会被获取重置为 100

基本上我需要访问 f单个值(用于递增)以及f的所有值在一起(用于重置)

我如何实现这个。此问题的演示可用 here 在 plunkr 中

HTML 片段

<body ng-controller="MainCtrl">
<counter-widget startnumber=1 resetter="reset"></counter-widget>
</body>

JS 片段

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope, $timeout) {
$scope.triggerReset = function () {
$scope.reset = true;
console.log('reset')
$timeout(function() {
$scope.reset = false;
},100)
}
});
app.directive("counterWidget",function(){
return{
restrict:"E",
scope:{
startnumber: '=',
resetter: '='
},
link:function(scope,elem,attr){
scope.f = 1;
scope.add = function(f){
this.f ++
}
scope.reset = function(){
scope.$parent.triggerReset()
}
scope.$watch(function(attr) {
return scope.resetter
},
function(newVal) {
if (newVal === true) {
scope.f = 100;
}
})

},
template:'<li ng-repeat="item in [1,2,3]">'+
"<button ng-click='add(f)'>+</button>"+
"{{f}}&nbsp&nbsp&nbsp"+
"<button ng-click='reset()'>reset</button><br><br>"+
'</li>'
}

})

最佳答案

ngRepeat 为每个项目创建一个新范围,因此您为每个项目获得一个新的 f。为了访问所有值,我建议将这些值存储在一个数组中并绑定(bind)到该数组。

http://plnkr.co/edit/amGSHZqCWsFgjl2bEM98

app.controller('MainCtrl', function($scope, $timeout) {
$scope.reset = function() {
$scope.values = []
for(var i = 0; i < 100; ++i) {
$scope.values.push({f: i});
}
}

$scope.reset();

});
app.directive("counterWidget",function(){
return{
scope:{
values: '=',
reset: '='
},
link:function(scope, elem, attr){
scope.add = function(value){
value.f++;
}
},
template:'<li ng-repeat="item in values">'+
"<button ng-click='add(item)'>+</button>"+
"{{item.f}}&nbsp&nbsp&nbsp"+
"<button ng-click='reset()'>reset all</button><br><br>"+
'</li>'
}
})

关于javascript - 如何更新 ng-repeat 中使用的变量的所有副本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29891321/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com