Showing ng-attributes in haml partials in Rails using jQuery ajax and $q

As I work on developing an Angular Frontend for an existing Rails Application, I have come across the challenge of integrating $q in my current setup. While I understand that transitioning to a REST API served directly to ngResource would be ideal, the complexity of the Ruby logic dispersed throughout the application makes this transition a daunting task at the moment.

My main concern lies in correctly handling ng attributes within the returned partials. The code snippet below illustrates the structure:

 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']

The HAML content is being rendered correctly on the page and the datepicker functionality is working as intended. A key point in the HAML code is:

 = form_for @type, :html=>{:class=>'form-horizontal type-form', :"ng-submit"=>"validateForm($event);"} do |f|

Interestingly, applying ng-attributes directly to raw DOM elements within HAML functions smoothly. For instance:

  = form_for @type, :html=>{:class=>'form-horizontal type-form', :"ng-controller"=>"someFormController"} do |f|

The above method fails while the below approach succeeds:

  = form_for @type, :html=>{:class=>'form-horizontal type-form', :"ng-controller"=>"someFormController"} do |f|
      %div(ng-controller=someFormController)

The service responsible for displaying functions as follows:

 Company.MyModule.factory 'TypeJQuery', ($q, $rootScope) ->
   multipart: (element) ->
     deferred = $q.defer()
     $.get "..." + element, (data) ->
       $rootScope.$apply ->
         deferred.resolve data
     deferred.promise

Despite these efforts, the submit action does not trigger and no logs are recorded. An alternative attempt made was:

   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'))")

Unfortunately, these changes did not yield any significant results.

I am seeking suggestions on how to tackle this issue effectively. Additionally, it's worth noting that further down in the returned partial there is another element with an ng-controller attribute that doesn't seem to respond as expected.

EDIT: The HAML content isn't directly returned but instead routed through the following js.erb file:

 $('div.form_<%= @artifact.id %>').replaceWith("<%=j render 'form' %>");

This process then delivers the form partial.

Answer №1

After reviewing the code snippet you've provided, it seems like there may be an issue with your validation logic.

In Angular, validation is typically handled through directives. If a form is marked as $invalid, it will not trigger the ng-submit event. Therefore, your validation function might not be executing as intended. The ng-submit event should be reserved for functions that need to be executed only when the form is valid.

For a better understanding of how form validation works in Angular, take a look at this example: http://plnkr.co/edit/B3joUY

If you require custom validation, you can achieve that by creating a custom validation directive. However, addressing custom validation is a separate topic altogether and would warrant a separate discussion.

Answer №2

Something interesting I've come across: Adding ng-attributes to Rails functions within templates like haml or erb does not seem to work, but adding them directly on a DOM element inside that partial works perfectly. Here's an example:

 = form_for @category, :html=>{:class=>'form-horizontal category-form', :"ng-controller"=>"someController"} do |f|

The above code snippet will fail silently and even though the controller is shown in the DOM inspection, it won't function as expected. However, this alternative approach does:

 = form_for @category, :html=>{:class=>'form-horizontal category-form'} do |f|
       %div(ng-controller=someController)

Does anyone know the reason behind this behavior and how we can work around this limitation to apply ng attributes directly on the rails function?

Answer №3

Here is the solution:

     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)

Make sure to include $compile in the controller as compile first.

Instead of returning jQuery, just return the HAML directly.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Retrieve and showcase JSON data with the help of jQuery

I'm trying to display a specific variable (Date) from a JSON file, but it doesn't seem to be working. Can anyone help me figure out what I'm doing wrong? <script type="text/javascript"> $(document).ready(function() { $. ...

Display a compilation either in the backend or the frontend

I'm fairly new to NodeJS and I could really use some advice. I currently have a webpage that displays a list of users, which is retrieved from a collection using Mongoose. I am aware of two different ways to display this list: 1) One option is to que ...

Are you ready to dive into the world of running an ASP.NET MVC project with Angular in Visual Studio

Currently, I am working on developing a CRUD application using ASP.NET MVC in Visual Studio with Angular. I am interested in running the entire project solely through VS Code without relying on Visual Studio. Does anyone have a solution for achieving thi ...

Having trouble with Cordova, Angular, and PushPlugin? Your callback isn't firing

While searching for solutions, I noticed various similar items but none were quite the same context as mine (Angular specifically, not using Ionic). My Cordova version is 5.0.0 (confirmed through 'cordova --version' in CMD showing 5.0.0, and in t ...

PHP-generated AngularJs Select Element

I'm facing an issue with my PHP function in my AngularJS application. I have created a function to select a default option, but it's not displaying the desired value. Here is the function code: function qtyList($selectName, $selectQty){ $st ...

Error message "e.nodename undefined when set to setTimeout" was encountered

I developed a unique piece of code for input boxes located at the top of different tables. By using a class='filt', the table can be filtered based on the inputs provided. However, most of the inputs consist of more than one letter, so I wanted t ...

delivering information to angular-ui modal while operating control as vm

I am facing an issue with passing an object to a modal controller. I have tried various approaches and here is my final code. Although the object is passed successfully, a significant error appears in the console. Error: [$injector:unpr] Below is the cod ...

transmit information to a PHP script

I am facing an issue while trying to transmit data to a PHP file. Below is the code I've written: App.js: .controller('sign_up', function ($scope, $http) { $scope.login = function () { var request = $http({ met ...

Learn the process of encoding a string in JavaScript or jQuery and then decoding it with PHP

I am facing an issue with updating a field in the database using Ajax and PHP. Everything runs smoothly except when there are special characters present, like this: اللهم اني اشكو اليك ضعف قوتي وقلة حيلتي وهواني عل ...

Transforming an ASP.NET webpage into a PDF format using Ajax Tab Container

I'm currently working on a website that involves a lot of data import and export. The user's data is being displayed in an ajax tab container, but I've run into an issue when trying to export this data to PDF: Script control 'TabPanel1 ...

Experimenting with Jasmine for testing an AngularJS service without the need for mocks

I am interested in utilizing Jasmine for writing tests (not unit tests) for an AngularJS service that acts as a wrapper for a REST API I developed on my server. The goal is to ensure that the service call reaches the server without requiring any form of mo ...

Acquiring data from an API response in JSON format using JavaScript

Utilizing a parse.com API server, I have successfully established communication in JavaScript through AJAX. The output from the response is being logged into the browser console with the following code: $.ajax(settings).done(function(response) { ...

The source for jQuery autocomplete is returning as null

Upon selection of a state and city by the user, an Ajax call is triggered to fetch data from the server. Once this data is retrieved, only then do I want to enable them to search through the results using jQuery UI autocomplete. I store the data in a varia ...

Conceal the element at all times

I'm facing a challenge with a paragraph element that is dynamically filled with content using Javascript. I need to hide the element whenever it doesn't have any text within it. However, I want to avoid using setTimeout or setInterval for this ta ...

Displaying foreign exchange rates using Shield UI Chart

In my quest to access and display forex data, I have stumbled upon the incredible Shield UI Chart. After some experimentation, I successfully mastered the art of implementing ajax: $.ajax({ url: 'http://api.apirates.com/jsonp/update', dataTy ...

Updating the text box's font color to its original black shade

I have a form that includes dynamic text boxes fetching data from the backend. When a user clicks on a text box, the color of the text changes. Upon form submission, a confirmation message is displayed and I want the text box color to revert back to black. ...

Tips for using the $each() function within a jquery append to retrieve object-based conditions for parameters

I encountered an issue while trying to include a condition in my endpoint, and I have recently started using jQuery for this purpose. Here is the code snippet from my Laravel view: <tbody id="tbody"> @foreach ($modul as $m) <tr> ...

Retrieve information from Angular service's HTTP response

Calling all Angular/Javascript aficionados! I need some help with a service that makes API calls to fetch data: app.service("GetDivision", ["$http", function($http){ this.division = function(divisionNumber){ $http.post("/api/division", {division:di ...

AngularJS Dilemma: Virtual Machine Data Set but No Rendering in Sight

Below is the AngularJS controller code written in Typescript: /// <reference path='../../definitions.d.ts' /> module baseApp.viewControls.products { export interface IProductsScope extends IAppScope { vm: { product ...

Sending a specified data type as an argument to a hyperlink

Is there a better way to create a parameter URL containing the same text that is typed into this text box? I am currently trying to achieve this but it doesn't seem to be working. <!DOCTYPE html> <html> <head> <script src=" ...