[英]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.