【问题标题】:angularjs json two way binding to text areaangularjs json 两种方式绑定到文本区域
【发布时间】:2016-08-04 11:25:49
【问题描述】:

我想以两种方式绑定到将包含 json 对象作为文本的文本区域,并且我应该能够以两种方式编辑 textarea 中的 json 对象。 working demo is here

<div ng-app="app">
  <div ng-controller="GeojsonController">
    <textarea ng-model="geojson"></textarea>
    <p>Geojson is: {{geojson | json}} </p>
  </div>
</div>

angular.module('app', [])
  .controller('GeojsonController', ['$scope', function($scope) {
    $scope.geojson = {
      "type": "FeatureCollection"
    };
  }]);

文本区内容为[object Object]

【问题讨论】:

标签: javascript angularjs json


【解决方案1】:
<textarea ng-model="geojson" ng-change="update()"></textarea>

$scope.geo = {
  "type": "FeatureCollection"
};
$scope.geojson = angular.toJson($scope.geo);

$scope.update = function() {
    $scope.geo = angular.fromJson($scope.geojson);
}

https://jsfiddle.net/f9fnetca/1/

附:为无效的 json 添加一些处理。

【讨论】:

【解决方案2】:

您可以使用$formatters$parsers 实现自定义指令

.directive('toJson', function() {
  return {
    require: 'ngModel',
    link: function(scope, elm, attrs, ctrl) {
     ctrl.$formatters.push(JSON.stringify);
    }
  }
});

&lt;textarea ng-model="geojson" to-json&gt;&lt;/textarea&gt;

查看自定义验证示例 in the docs 以获得更好的想法。

【讨论】:

    【解决方案3】:

    您想使用ng-model 中的$formatters$parsers 在模型中的对象和输入中显示的文本之间进行双射。

    希望通过使用控制器功能会更简单。您显示文本并处理对象。 getJson() 方法完成工作

    <div ng-app="app">
      <div ng-controller="GeojsonController">
        <textarea ng-model="geojson"></textarea>
        <p>Geojson is: {{getJson(geojson) | json}} </p>
      </div>
    </div>
    

    然后:

    angular.module('app', [])
      .controller('GeojsonController', ['$scope', function($scope) {
        $scope.geojson = '{"type": "FeatureCollection"}';
    
        $scope.getJson = function(){
            return JSON.parse($scope.geojson);
        }
      }]);
    

    这里是 JSFiddle:https://jsfiddle.net/bbhoey5g/6/

    【讨论】:

      猜你喜欢
      • 2014-02-13
      • 2016-02-27
      • 1970-01-01
      • 1970-01-01
      • 2013-11-29
      • 2017-01-15
      • 2013-09-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多