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

问题描述 投票:0回答:2

这是我的朋克,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

javascript angularjs angularjs-directive
2个回答
0
投票

您可以在数组上使用$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
-->

0
投票

一个人可以对数组使用格式化程序和解析器的自定义指令:

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

有关更多信息,请参阅

© www.soinside.com 2019 - 2024. All rights reserved.