2016-12-03 51 views
0

我有以下輸入(嵌套在ng-repeat中)。ng-list可以返回一個數字而不是字符串數組嗎?

<input ng-model="event.days" ng-list required> 

的問題是,每當用戶編輯該輸入的值(例如,改變:

1, 2 

1, 2, 3 

從整數數組的數組的變化,像

[1, 2, 3] 

到一串字符串

["1", "2", "3"] 

我意識到文檔清楚地指出這是ng-list的作用。我只是想知道這個問題最緊張的解決方法是什麼。我已經嘗試添加:

ng-change="event.days = event.days.map(parseInt);" 

但是這並沒有奏效。

回答

0

可以克隆ngList你讓我們說intList中指令,並且只需添加有parseInt功能:

app.directive('intList', function() { 
    return { 
    restrict: 'A', 
    priority: 100, 
    require: 'ngModel', 
    link: function(scope, element, attr, ctrl) { 
     var ngList = attr.ngList || ', '; 
     var trimValues = attr.ngTrim !== 'false'; 
     var separator = trimValues ? ngList.trim() : ngList; 

     var parse = function(viewValue) { 
     // If the viewValue is invalid (say required but empty) it will be `undefined` 
     if (!angular.isDefined(viewValue)) return; 

     var list = []; 

     if (viewValue) { 
      angular.forEach(viewValue.split(separator), function(value) { 
      if (value) list.push(parseInt(trimValues ? value.trim() : value)); 
      }); 
     } 

     return list; 
     }; 

     ctrl.$parsers.push(parse); 
     ctrl.$formatters.push(function(value) { 
     if (angular.isArray(value)) { 
      return value.join(ngList); 
     } 

     return undefined; 
     }); 

     // Override the standard $isEmpty because an empty array means the input is empty. 
     ctrl.$isEmpty = function(value) { 
     return !value || !value.length; 
     }; 
    } 
    }; 
}); 

plunker: http://plnkr.co/edit/mEBm05gnfyM03xy9QlZh?p=preview

+0

這完美的作品。我從來沒有想過只是克隆/定製ng-list! – Nick

0

這不是ng-list的行爲。 input的值始終是一個字符串,因此這將是event.days

你總是可以做一些分析,如:

daysArray = daysString.split("\\s+").map(day => parseInt(day, 10)) 
+0

好的我明白了!但我可以在哪裏放置類似的東西?它不起作用。 – Nick

相關問題