AngularJS:textarea 绑定到 JSON 对象显示“对象-对象"; [英] AngularJS: textarea bind to JSON object shows "object-object"

查看:77
本文介绍了AngularJS:textarea 绑定到 JSON 对象显示“对象-对象";的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对 AngularJS 还很陌生.

I am fairly new to AngularJS.

我正在尝试将对象绑定到文本区域.

I am trying to bind an object to a 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(然后再次将其另存为对象)?

How can I show the JSON stringified (and later save it as an object again)?

推荐答案

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

You need a custom directive that parses the input to an object, and displays the object as a string, respectively:

类似于:

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/

这篇关于AngularJS:textarea 绑定到 JSON 对象显示“对象-对象";的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆