所以我正在为预先存在的Rails应用程序编写一个Angular前端。我理解使用$ q充其量只是一个中间步骤,然后转换后端通过JSON直接向REST服务器提供REST Api,但遗憾的是暂时存在于各种Ruby位置的逻辑太多,很容易将所有内容重写为纯粹的角度格式。
问题是,如何在返回的部分中正确实例化和处理ng属性。以下是代码的清理版本。
Company.Controller.TypeAccordionController = (scope, http, element, q, typeJQueryService) ->
scope.validateForm = (event) ->
console.log "we are here"
scope.getTheDamnType = (id) ->
typeJQueryService.multipart(id).then (response)->
angular.element('.datePicker').datepicker()
Company.Controller.TypeAccordionController.$inject = ['$scope', '$http', '$element', '$q','typeJQuery']
返回的HAML正在页面上正确显示,并且正在成功实例化datepicker。返回的HAML的第一行是:
= form_for @type, :html=>{:class=>'form-horizontal type-form', :"ng-submit"=>"validateForm($event);"} do |f|
有趣的旁注:在HAML中将ng-attributes放在原始DOM元素上就像魅力一样。例如:
= form_for @type, :html=>{:class=>'form-horizontal type-form', :"ng-controller"=>"someFormController"} do |f|
上述方法无效。下面的作品就像一个魅力:
= form_for @type, :html=>{:class=>'form-horizontal type-form', :"ng-controller"=>"someFormController"} do |f|
%div(ng-controller=someFormController)
进行显示的服务如下:
Company.MyModule.factory 'TypeJQuery', ($q, $rootScope) ->
multipart: (element) ->
deferred = $q.defer()
$.get "..." + element, (data) ->
$rootScope.$apply ->
deferred.resolve data
deferred.promise
但是,提交时没有任何反应,日志不会打印。另一种尝试是:
scope.validateForm = (event) ->
console.log "we are here"
scope.getTheDamnType = (id) ->
typeJQueryService.multipart(id).then (response)->
angular.element('.datePicker').datepicker()
angular.element('form').attr("ng-submit", "validateForm($(this).attr('id'))")
同样没什么用处发生的。
有关如何解决此问题的任何建议?在旁注:后面的返回部分中有另一个元素,其上有一个ng-controller。毋庸置疑,有用的事情不会发生在它身上。
编辑:HAML实际上并没有返回原始状态,而是通过以下js.erb路由:
$('div.form_<%= @artifact.id %>').replaceWith("<%=j render 'form' %>");
然后返回表单partial。
答案 0 :(得分:1)
我需要查看您正在输出的其余HTML,但是我可以告诉您它看起来您的验证错误。
Angular中的验证通常由指令完成。如果表单是$ invalid,它将永远不会命中ng-submit,因此永远不会调用您的验证函数。如果你的表单有效,那么ng-submit应该是你想要的任何函数。
在Angular中看一下表单验证的演示:
如果您需要一些自定义验证,那也是可行的,它只需要一个自定义验证指令。但这是一个完全不同的问题。
答案 1 :(得分:0)
有趣的说明我发现:在模板中设置rails函数的属性(haml,erb,等等)似乎不起作用,而直接在该部分内的DOM元素上设置它就可以了。例如:
= form_for @type, :html=>{:class=>'form-horizontal type-form', :"ng-controller"=>"someFormController"} do |f|
以上操作不起作用,它将无声地失败并且DOM检查将显示在窗体元素上显示控制器,它将无法正常工作。以下是:
= form_for @type, :html=>{:class=>'form-horizontal type-form'} do |f|
%div(ng-controller=someFormController)
任何人都知道为什么是/如何解决这个限制并将ng属性直接放在rails函数上?
答案 2 :(得分:0)
答案如下:
typeJQueryService.multipart(id).then (response)->
scope.form = compile(response.substring(response.indexOf("<form"), response.lastIndexOf("</form>")))(scope)
angular.element("div.form_" + id).parent().html compile(scope.form)(scope)
显然首先将$ compile注入控制器。
然后,而不是返回jQuery,直接返回HAML。