2016-03-24 35 views
0

したがって、入力を文字列の配列にバインドできるAngularディレクティブを作成しました。しかし、配列からプログラムで項目を削除しようとするたびに、モデルは入力フィールドに反映されません。 $ modelValueも更新されていないようです。誰かが角度がこのようにふるまう理由を説明することはできますか? popの機能が変更されたイベントの配列をトリガしていないようだhttp://jsfiddle.net/r19mbv1r/ngModelの変更時に入力フィールドが更新されない

+0

ここで、このupdaedフィドルを確認してください。 http://jsfiddle.net/r19mbv1r/1/ – vijaykumar

答えて

1

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

関連する問題