Angular 模式表单从 JSON 加载数据

Angular Schema Form Load Data from JSON

我是一名硬件工程师,正在尝试创建内部软件工具。我以为我可以很容易地做到这一点,但是有太多的未知数让我无法进步。

我正在尝试创建用于管理订单的内部软件解决方案。我定义了一个有效的 JSON 架构。

我想建立一个网页,我可以在其中通过填写网络表格来创建新订单。然后应将数据存储为 JSON 文本文件。我还希望能够加载 JSON 文本文件,用当前值预填充表单,进行一些更改,然后保存更改。

我在 php 和 mysql 中做过类似的事情,但我想使用 JSON 文件来更改软件工具,而不必 fiddle 左右同一个数据库结构。我也认为这是一个很好的学习机会。

我正在尝试使用自动生成的表单 (schemaform.io),并且我已经使用了以下代码:

<!DOCTYPE html>
<html >

  <head>    

  </head>

  <body ng-app="test" ng-controller="FormController">

    <form name="ngform"
          sf-schema="schema"
          sf-form="form"
          sf-model="model"></form>

<script type="text/javascript" src="../bower_components/angular/angular.js"></script>
<script type="text/javascript" src="../bower_components/angular-sanitize/angular-sanitize.min.js"></script>
<script type="text/javascript" src="../bower_components/tv4/tv4.js"></script>
<script type="text/javascript" src="../bower_components/objectpath/lib/ObjectPath.js"></script>
<script type="text/javascript" src="../bower_components/angular-schema-form/dist/schema-form.min.js"></script>
<script type="text/javascript" src="../bower_components/angular-schema-form/dist/bootstrap-decorator.min.js"></script>    

<script type="text/javascript" src="../bower_components/jquery/dist/jquery.js"></script>    


</script>
 
<script>

/*
$.getJSON("data/order.json", function(orderTemplateJson) {
    console.log(orderTemplateJson); // this will show the info it in firebug console
 $scope.$broadcast('schemaFormRedraw')
});
*/

var app = angular.module('test',['schemaForm']);
app.controller('FormController', function($scope,$http){
   $scope.schema = {
   // A long long string of text goes here
};

  $scope.form = [
    "*",
    {
      type: "submit",
      title: "Save"
    }
  ];

  $scope.model = {};
})
    </script>

  </body>

</html>

我现在想从文件加载 JSON 模式。我试图将代码移动到 getJSON 调用的回调中,但我收到以下错误消息:

未捕获错误:[$injector:modulerr] 由于以下原因无法实例化模块测试: 错误:[$injector:nomod] 模块 'test' 不可用!您要么拼错了模块名称,要么忘记加载它。如果注册模块,请确保将依赖项指定为第二个参数。

$.getJSON("data/order.json", function(orderTemplateJson) {
    console.log(orderTemplateJson); 
  
    //Moved all the angular module code to here
});

我尝试了各种方法,但问题很可能是我真的不知道自己在做什么。任何帮助将不胜感激。

此外,是否有人对我如何使用包含数据(并符合模式)的 JSON 文件中的数据预加载表单有任何指示?

谢谢..

/马丁

在使用 angular 时,最好按照 angular 的方式来做事。所以首先你应该使用 angular 的 $http 来加载文件而不是 jQuery 的 $.getJSON。所以在你的控制器中你可以这样做:

app.controller('FormController', function($scope,$http){
   $http.get("data/order.json").then(
      function success(response) {
        // please note that as this is asynchronous, 
        // the $scope.schema will be available after response
        // has been received but this should be ok
        $scope.schema = angular.fromJson(response.data);
      },
      function error(response) { /* handle error */ });
   // do other stuff
});

然后 angular $http API reference 会有帮助

使用 angular 还有其他一些事情需要考虑,但是值得花一些时间来熟悉 angular 方式 并相对快速地从中受益.

更有帮助的是使用 $resource 而不是 $http,因为它专用于处理 json(实际上是 REST)。