Javascript 将输入字段中的数组显示为数组

Javascript 将输入字段中的数组显示为数组,javascript,angularjs,angularjs-directive,Javascript,Angularjs,Angularjs Directive,这是我的扑克牌, 名单: 名称={{names}} $scope.names是一个数组,当用于在html的输入字段中显示时,它显示为morpheus,neo,trinity 但如何在html输入字段中将其显示为[“morpheus”、“neo”、“trinity”] 在输入字段的数组中添加或删除元素时,使用新值更新$scope.names您可以在数组中使用$scope.$watchCollection,或在输入字段中使用$scope.watch,然后根据更新的方式,使用JSON.stri

这是我的扑克牌,


名单:

名称={{names}}
$scope.names
是一个数组,当用于在html的输入字段中显示时,它显示为
morpheus,neo,trinity
但如何在html输入字段中将其显示为
[“morpheus”、“neo”、“trinity”]


在输入字段的数组中添加或删除元素时,使用新值更新$scope.names

您可以在数组中使用
$scope.$watchCollection
,或在输入字段中使用
$scope.watch
,然后根据更新的方式,使用
JSON.stringify
JSON.parse

(函数(角度){
"严格使用",;
angular.module('listExample',[])
.controller('ExampleController',['$scope',function$scope){
$scope.names=['morpheus','neo','trinity'];
$scope.value=JSON.stringify($scope.names)
$scope.$watch(“值”,函数(){
试一试{
$scope.names=JSON.parse($scope.value)
}捕获(e){}
})
$scope.$watchCollection(“名称”,函数(){
$scope.value=JSON.stringify($scope.names)
})
$scope.addName=函数(){
$scope.names.push('mr.anderson');
}
}]);
})(窗口角度);
/*
2019谷歌公司版权所有。保留所有权利。
此源代码的使用受MIT风格的许可证管理,该许可证
可以在以下位置的许可证文件中找到:http://angular.io/license
*/

名单:
试验

名称={{names}}

可以将自定义指令与数组的格式化程序和解析器一起使用:

app.directive('toFromArray', function(){
  return{
    require: 'ngModel',
    link: function(scope, elem, attrs, ctrl) {
      ctrl.$parsers.push(toArray);
      ctrl.$formatters.push(fromArray);

      function toArray(viewValue){       
        return viewValue && viewValue.split(',');
      }
      function fromArray(model) {
        console.log(model);
        return model.join();
      }
    }
  };
})
用法

有关详细信息,请参阅

<body ng-app="listExample">
  <form name="myForm" ng-controller="ExampleController">
  <label>List: <input name="namesInput" ng-model="names" required></label>

  <br>
  <tt>names = {{names}}</tt><br/>

 </form>
</body>
app.directive('toFromArray', function(){
  return{
    require: 'ngModel',
    link: function(scope, elem, attrs, ctrl) {
      ctrl.$parsers.push(toArray);
      ctrl.$formatters.push(fromArray);

      function toArray(viewValue){       
        return viewValue && viewValue.split(',');
      }
      function fromArray(model) {
        console.log(model);
        return model.join();
      }
    }
  };
})
<input name="namesInput" ng-model="names" to-from-array>