:
<input array-model ng-model="inputList">
<button type="button" ng-click="removeLastItem()">
Remove last element from the list
</button>
$scope.removeLastItem = function() {
$scope.inputList.pop();
};
はここにフィドルを参照してください。
明らかに、$ formattersは$watch
ではなく$WatchCollection
の原則で動作します。
これを修正できます。配列要素を削除して初期化を行うたびに、
ライブサンプルjsfiddleです。
angular.module('SomeApp', [])
.controller('SomeAppController', function($scope) {
$scope.inputList = [];
$scope.removeLastItem = function() {
$scope.inputList = $scope.inputList.slice(0,$scope.inputList.length-1);
};
})
.directive('arrayModel', function() {
return {
restrict: 'A',
require: 'ngModel',
link: function(scope, iElement, iAttrs, ngModel) {
ngModel.$formatters.push(function(modelValue) {
console.log("Inside formatters!",modelValue);
return modelValue.join(',');
});
ngModel.$parsers.push(function(viewValue) {
console.log("Inisde parsers",viewValue);
return viewValue.split(',');
});
\t \t \t \t
}
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="SomeApp" ng-controller="SomeAppController" class="container">
<h4>
Input a comma separated string
</h4>
<input array-model ng-model="inputList">
<br/> Input List is :{{inputList}}.
<br/>
<button type="button" ng-click="removeLastItem()">
Remove last element from the list
</button>
</div>
ここで、このupdaedフィドルを確認してください。 http://jsfiddle.net/r19mbv1r/1/ – vijaykumar