[英]AngularJS : Retrieving data to a directive from a factory function
在這里,我對AngularJS的學習道路又提出了一個問題。
在這個社區的幫助下,我得以實現自己想要完成的工作的簡單版本。 基本上,將數據添加到一個地方的工廠功能中,並能夠在App的另一個地方渲染為模態。 JSFiddle
但是,盡管我可以使其在較小的版本上運行,但不能在“真實”應用程序上運行。
該應用程序的想法非常簡單:某些管理員用戶可以創建一系列表單,供應用程序用戶使用,以通過填充並遵循批准流程來請求通過他們的東西。
在應用程序的一部分中,只有具有訪問權限的管理員用戶才能編輯表單,而在普通用戶填充表單時,應用程序的其他部分才可以編輯。 有一個表單工廠函數,包含並封裝模塊對表單的使用,並臨時存儲一個表單的數據(直到我實現將代碼存儲在mongo中)。
該模式在應用程序開始時就很好用了,因為如果我將其放在代碼的其他部分上並沒有按預期工作,因為我也在使用Bootstrap選項卡。
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"></button>
<h4 class="modal-title" id="myModalLabel">Modal title</h4>
</div>
<div class="modal-body">
<peek-form-directive></peek-form-directive>
<render-form></render-form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
如您所見,我在模式框內有2個指令
<peek-form-directive></peek-form-directive>
<render-form></render-form>
peekFormDirective是一個非常簡單的指令,它僅嘗試檢索數據並將其顯示在瀏覽器上
.directive('peekFormDirective', function (FormServ) {
return {
scope: {},
template: "<pre>{{formData}}</pre>",
restrict: 'E',
link: function (scope, elem, attrs) {
scope.formData = FormServ.currentFormData.getAllItems();
}
};
});
雖然渲染形式非常相似,但是迭代組件並逐一渲染。
我無法弄清楚的部分是,如果我在可以編輯表單的頁面上而不是在模態頁面上使用這些指令,為什么這些指令可以很好地工作。 在該編輯頁面上,我將指令放置在控制器外部,就像在模態中一樣。
因此,例如,在該編輯頁面中,指令peekFormDirective顯示以下結果:
[{"order":1,"itemType":"title","data":{"order":0,"itemType":"","data":{},"label":"a"}}]
當我單擊同一頁面上的按鈕以打開模態時,結果它始終是一個空數組[]。
最初,我堅信范圍可能是一個問題,但我認為並非如此,因為無論如何我都是從工廠函數中檢索數據的。
為什么我可以在編輯頁面上而不是在模式頁面上使用預期的指令?
您的問題是stdFormCtrl
中的指令<peek-form-directive>
和<render-form>
使用的是與模態中的Template
對象不同的Template
對象,因此getAllItems
將返回不同的數組。 因此,在您的stdFormCtrl
:
if (!$scope.template) {
var templateList = [];
// You were creating a new template here.
// Comment this out and you'll see changes reflected in your modal
// FormServ.currentFormData = new FormServ.Template(templateList);
$scope.template = FormServ.currentFormData;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.