在我當前的項目中,我需要使用AngularJS創建一個動態表單。 我已經按照這個視頻的想法構建了表格here.不同字段類型的angularjs動態表單
我似乎無法將提交的數據返回給我的控制器。我只在控制檯日誌中收到未定義的內容。
當前表單的數據在加載狀態之前在ui-router中解析,然後複製到控制器的數據屬性中。
與視頻不同,我們的表單要求將問題分解爲多個部分。
數據中的每個部分都有一個ng重複,然後嵌套的ng-repeat遍歷每個問題。確定類型,並通過ng-switch加載問題/字段類型的正確指令。
我掀起了一個小Plunker來幫助說明。 https://plnkr.co/edit/6dCnHiFDEYu03kfX07mr
最後還有一些類型,我不確定如何處理,如地址或電話號碼,這將被視爲一個問題類型,但有多個領域。
(如[街] [市] [狀態] [郵編])
控制器
namespace portal.dashboard.form{
class formCtrl{
formData: portal.domain.interfaces.IHousingRequest;
static $inject = ["formResolve"];
constructor(private formResolve:any) {
this.formData= this.loadHousingRequestFormData;
}
public submit(isValid,data) {
if (isValid) {
console.log(data);
}
}
}
angular
.module("portal")
.controller("formCtrl", formCtrl);
}
指令輸入型文本
namespace portal.directives {
function inputText(): ng.IDirective {
return {
scope: {
model: '='
},
controller: function ($scope: ng.IScope) {
var directiveScope = $scope.$parent.$parent;
},
controllerAs:'vm',
templateUrl: 'form/templates/input-text.html'
}
}
angular
.module("portal")
.directive("inputText", inputText);
}
輸入型HTML
<input type="text"
ng-model="model"/>
HTML
<form name="form" ng-submit="vm.submit(form.$valid, data)" novalidate>
<!-- Section repeat -->
<div ng-repeat="section in vm.formData.sections track by $index">
<section>
<div>
<h4>
{{section.name}}<br />
<small ng-show="section.description">{{section.description}}</small>
</h4>
</div>
<section>
<!-- Section questions repeat -->
<div ng-form="formFields" ng-repeat="field in section.fields track by $index">
<label>
{{field.name}}<br />
<small>{{field.description}}</small>
</label>
<!-- input field switch -->
<div ng-switch="field.type">
<div ng-switch-when="Text">
<input-text model="data.answer[$index]">
</input-text>
</div>
<div ng-switch-when="Email">
<input-email model="data.answer[$index]">
</input-email>
</div>
</div>
</div>
</section>
</section>
</div>
<div>
<button type="submit">Submit</button>
</div>
</form>
你是對的,這是不需要的,我鏈接到的視頻也鏈接到github頁面。正如我引用的那樣,我只是認爲它做了一些事情,但回過頭來看,我發現我並不需要它,因爲我打算構建表單。 – gboh
@gboh很高興它幫助你:) –