How to update all copies of a variable used in ng-repeat

I need to increase the corresponding value by pressing a button +

,
but at the same time by pressing any button reset

, I need to reset all values ​​to 100.

Currently I can increase the corresponding value when the button is clicked +

, but when the button is clicked, reset

only the values ​​that have not been increased get reset to100

Basically, I need to get access to a single value f

(for the increment), and all the values of f

together (to reset)

How to implement it. A demo of this problem is available here on plunkr

HTML snippet

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

      

JS snippet

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>'
    }

  })

      

+3


source to share


1 answer


ngRepeat creates a new region for each item, so you get a new one f

for each item. To access all the values, I suggest storing the values ​​in an array and bind to that array.

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>'
    }
  })

      

+1


source







All Articles