0

What is the easiest way in angular to bind one value to an array of values so that all array items get the same value e.g. of an input when it changes.

<script>
     var myArray= [1,1,1];  
</script>

<input ng-model="myArray" type="text" />
3
  • Do you have a particular use-case for this? It seems very inefficient to be storing the same data multiple times - maybe there is a better way to solve your problem? Commented Sep 26, 2014 at 8:38
  • Is this Array a fixed length one or dynamic? Commented Sep 26, 2014 at 8:42
  • it is dynamic. Leon answered already. Thanks Commented Sep 26, 2014 at 8:45

2 Answers 2

2

Could use the ngChange directive to call a function binding the new value to all the elements:

 angular.module('changeExample', [])
   .controller('ExampleController', ['$scope',
     function($scope) {
       $scope.valueToCopy = '';
       $scope.values = values = [1, 1, 1, 3, 6];
       $scope.change = function() {
         for (var i = values.length - 1; i >= 0; i--) {
           values[i] = $scope.valueToCopy;
         }
         console.log(values);
       };
     }
   ]);
<div ng-app="changeExample" ng-controller="ExampleController">
  Copy this:
  <input ng-model="valueToCopy" ng-change="change()" />

  <ul>
    <li ng-repeat="value in values track by $index">Element at {{$index}} = {{value}}</li>
  </ul>
</div>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

Sign up to request clarification or add additional context in comments.

Comments

0

you can $watch the value of the input variable, and then update the array, something like this:

app.controller('MainCtrl', function($scope) {
  $scope.myArray = [];

  $scope.$watch('arrayValue', function(val){
    $scope.myArray = [val,val,val];
  })
});
------------------------------------------
<input type="text" ng-model="arrayValue">
{{ myArray }}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.