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" />
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" />
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>
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 }}