在输入字段中将数组显示为数组

这是我的朋克, https://plnkr.co/edit/stKf1C5UnCKSbMp1Tyne?p=preview

angular.module('listExample',[])
  .controller('ExampleController',['$scope',function($scope) {
    $scope.names = ['morpheus','neo','trinity'];
}]);
<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>

$scope.names是一个数组,当用于显示在html的输入字段中时,它显示为morpheus,neo,trinity 但是如何在html输入字段

中将其显示为["morpheus","neo","trinity"]

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

zyc007 回答:在输入字段中将数组显示为数组

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

(function(angular) {
  'use strict';
angular.module('listExample',[])
  .controller('ExampleController',['$scope',function($scope) {
    $scope.names = ['morpheus','neo','trinity'];
    $scope.value = JSON.stringify($scope.names)
    $scope.$watch("value",function() {
        try {
          $scope.names = JSON.parse($scope.value)  
        } catch (e) {}
    })
    $scope.$watchCollection("names",function() {
       $scope.value = JSON.stringify($scope.names)
    })
    $scope.addName = function() {
      $scope.names.push('mr. anderson');
    }
  }]);
})(window.angular);

/*
Copyright 2019 Google Inc. All Rights Reserved.
Use of this source code is governed by an MIT-style license that
can be found in the LICENSE file at http://angular.io/license
*/
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<!doctype html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <script src="//code.angularjs.org/1.7.9/angular.min.js"></script>
  <script src="app.js"></script>
  

  
</head>
<body ng-app="listExample">
  <form name="myForm" ng-controller="ExampleController">
  <label>List: <input name="namesInput" ng-model="value" required></label>
  <button ng-click="addName()">Test</button>
  <br>
  <tt>names = {{names}}</tt><br/>
  
 </form>
</body>
</html>

<!-- 
Copyright 2019 Google Inc. All Rights Reserved.
Use of this source code is governed by an MIT-style license that
can be found in the LICENSE file at http://angular.io/license
-->

,

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

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>

DEMO on PLNKR

有关更多信息,请参见

本文链接:https://www.f2er.com/3026190.html

大家都在问