Reputation: 1848
I try to manage an array with an input List.
I'd like the user to be able to add an item only if the last one is not empty. I don't understand why I can't bind the change of the array.
I tried the same kind of code completely in the html, but doesn't work better.
Where am I wrong ?
Here is a plunker : http://plnkr.co/edit/IpivgS5TWNQFFxQlRloa?p=preview
HTML
<div class="row" ng-repeat="radio in radioList track by $index">
<p class="input-group">
<input type="text" class="form-control" ng-model="radio.code" placeholder="enter sthg" ng-required="true" />
<span class="input-group-btn">
<button type="button" class="btn btn-default" ng-click="removeRadioList($index);"><i class="glyphicon glyphicon-remove">X</i>
</button>
</span>
</p>
</div>
</div>
<div class="col-xs-3">
<button class="btn btn-primary" ng-click="addRadioList();" ng-disabled="disableAddRadio">Ajouter un cliché</button>
{{radioList[radioList.length-1] }}
</div>
**JS **
$scope.radioList = [{
code: ''
}];
$scope.addRadioList = function() {
$scope.radioList.push({
'code': ''
});
}
$scope.removeRadioList = function(i) {
$scope.radioList.splice(i, 1);
}
$scope.$watch('radioList', function(newValue, oldValue) {
console.log('change');
$scope.disableAddRadio = (angular.isDefined($scope.radioList[$scope.radioList.length - 1].code) || $scope.radioList.length < 1);
});
Upvotes: 0
Views: 41
Reputation: 3326
The correct watch for an array is:
$scope.$watchCollection
Then you should check the newVal coming into the function in order to apply some logic (coming as an array). Example:
if ( newValue.length > 1 && newValue[newValue.length-2].code === undefined ) $scope.disableAddRadio = true;
Here your plunker updated: http://plnkr.co/edit/tf2SSoWNaXSXaZqvRkQT?p=preview
Upvotes: 1