AngularJS:textarea绑定到JSON对象显示“object-object”

时间:2013-07-27 02:36:22

标签: angularjs

我对AngularJS很新。

我正在尝试将对象绑定到textarea。

HTML:

<textarea rows="5" cols="10" ng-model="menuItem.preset"></textarea>

型号:

{
    "kind": "title",
    "label": "ADD_TITLE",
    "iconSrc": "textTitle.png",
    "experimentInclude": "",
    "experimentExclude": "three",
    "preset": {
        "compType": "richTitle",
        "styleId": "txtNew"
    }
}

结果:

json shown as object

如何显示字符串化的JSON(稍后再将其另存为对象)?

9 个答案:

答案 0 :(得分:28)

您需要一个自定义指令来解析对象的输入,并将对象分别显示为字符串:

类似的东西:

angular.module('yourApp').directive('jsonText', function() {
    return {
        restrict: 'A',
        require: 'ngModel',
        link: function(scope, element, attr, ngModel) {            
          function into(input) {
            return JSON.parse(input);
          }
          function out(data) {
            return JSON.stringify(data);
          }
          ngModel.$parsers.push(into);
          ngModel.$formatters.push(out);

        }
    };
});
<textarea json-text rows="5" cols="10" ng-model="menuItem.preset"></textarea>

小提琴:http://jsfiddle.net/HzYQn/

答案 1 :(得分:25)

我刚刚研究了我认为最合适的方式,因为我需要https://github.com/vorburger/MUI.js ...所以here is a Plonker我的解决方案。它基于&amp;本质上是一个特殊情况(即应用程序)相关的Q How to do two-way filtering in angular.js?附加的扭曲是模型更新也应该改变文本框..这就是$ watch / $ setViewValue / $渲染事物的作用。

var app = angular.module('app', []);

app.directive('jsonText', function() {
  return {
    restrict: 'A', // only activate on element attribute
    require: 'ngModel', // get a hold of NgModelController
    link: function(scope, element, attrs, ngModelCtrl) {

      var lastValid;

      // push() if faster than unshift(), and avail. in IE8 and earlier (unshift isn't)
      ngModelCtrl.$parsers.push(fromUser);
      ngModelCtrl.$formatters.push(toUser);

      // clear any invalid changes on blur
      element.bind('blur', function() {
        element.val(toUser(scope.$eval(attrs.ngModel)));
      });

      // $watch(attrs.ngModel) wouldn't work if this directive created a new scope;
      // see https://stackoverflow.com/questions/14693052/watch-ngmodel-from-inside-directive-using-isolate-scope how to do it then
      scope.$watch(attrs.ngModel, function(newValue, oldValue) {
        lastValid = lastValid || newValue;

        if (newValue != oldValue) {
          ngModelCtrl.$setViewValue(toUser(newValue));

          // TODO avoid this causing the focus of the input to be lost..
          ngModelCtrl.$render();
        }
      }, true); // MUST use objectEquality (true) here, for some reason..

      function fromUser(text) {
        // Beware: trim() is not available in old browsers
        if (!text || text.trim() === '') {
          return {};
        } else {
          try {
            lastValid = angular.fromJson(text);
            ngModelCtrl.$setValidity('invalidJson', true);
          } catch (e) {
            ngModelCtrl.$setValidity('invalidJson', false);
          }
          return lastValid;
        }
      }

      function toUser(object) {
        // better than JSON.stringify(), because it formats + filters $$hashKey etc.
        return angular.toJson(object, true);
      }
    }
  };
});


app.controller('Ctrl', ['$scope',
  function($scope) {
    $scope.model = {};
    $scope.model.data = {
      "kind": "title",
      "label": "ADD_TITLE",
      "iconSrc": "textTitle.png",
      "experimentInclude": "",
      "experimentExclude": "three",
      "preset": {
        "compType": "richTitle",
        "styleId": "txtNew"
      }
    };
  }
]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<div ng-app="app" class="container">
  <div ng-controller="Ctrl" class="row">
    <textarea json-text ng-model='model.data' rows="15"></textarea>
    <p>{{ model.data }}</p>
  </div>
</div>

答案 2 :(得分:11)

尝试使用json过滤器

<textarea rows="5" cols="10" >
   {{ menuItem.preset | json }}
</textarea>

答案 3 :(得分:5)

这是我们的JSON指令,带有效性检查:

app.directive('jsonInput', function () {
  'use strict';
  return {
    restrict: 'A',
    require: 'ngModel',
    link: function (scope, elem, attr, ctrl) {
        ctrl.$parsers.unshift(function(input) {
          try {
            var obj = JSON.parse(input);
            ctrl.$setValidity('jsonInput', true);
            return obj;
          } catch (e) {
            ctrl.$setValidity('jsonInput', false);
            return null;
          }
        });
        ctrl.$formatters.unshift(function(data) {
          if (data == null) {
            ctrl.$setValidity('jsonInput', false);
            return "";
          }
          try {
            var str = JSON.stringify(data);
            ctrl.$setValidity('jsonInput', true);
            return str;
          } catch (e) {
          ctrl.$setValidity('codeme', false);
              return "";
          }
        });
    }
  };

});

当用户输入无效的JSON时,模型为空。当模型包含循环引用或为null时,用户将看到一个空字符串(“”)并且输入无效。

享受。

答案 4 :(得分:3)

您也可以在模型上定义toString方法:

  $scope.menuItem.preset.toString = function(){
        return JSON.stringify(this);
    }

http://jsfiddle.net/ceJ4w/19/

然后同步回使用手表

http://jsfiddle.net/ceJ4w/20/

但它看起来更像是肮脏的黑客而非解决方案

答案 5 :(得分:1)

使用ng-change事件太乱了吗?

<textarea ng-model="textmainboardJSON" ng-change="updateMainboard()"

http://jsfiddle.net/gsw9Q/3/

答案 6 :(得分:0)

您可以分两步完成:

答案 7 :(得分:0)

试试这个。它适用于我的情况

<textarea rows="5" cols="10" >{{menuItem.preset}}</textarea>

答案 8 :(得分:0)

我有简单的方法将数组数据绑定到angularjs中的文本区域。如果有两个数组,则需要并行显示。此外,您也可以在jsfiddle上获得它。

http://jsfiddle.net/Ahsan_Aftab/bc7hd258/18/

<!DOCTYPE html>
    <html>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js">
    <body>

    <div ng-app="myApp" ng-controller="myCtrl">


            <textarea ng-model="TextAreacodeGroups" style="width:52%;height:200px;" columns="25" id="code_groups">

        {{CodeGroupsFun()}}

       </textarea>

    </div>

<script>

    var app = angular.module('myApp', []);

    app.controller('myCtrl', function($scope) {
        var combined;
        var array1=['01','02','03','04'];
        var array2= ['Students','Teachers','Managers','Operators'];

     $scope.CodeGroupsFun = function () {

     $scope.TextAreacodeGroups =
      combined = array1.map(function (e, i) {
       return '\n' + array1[i] + '     -     ' + array2[i];
                    });
                };
    });

</script>    
    </body>
    </html>