Issue with Angular: Unable to update model before modal closure on submit

I have a search form that is displayed within a modal window created using Angular UI Bootstrap. The input fields in the form update the ng-model when submitted.

<script type="text/ng-template" id="mobileSearchPanel">
              <form>
              <h1 style="text-align:center;">Search</h1>
                <div id="mobileSearcher">
                  <div ng-repeat="attobj in columns">
                    <input ng-if="attobj.filterable" type="text" class="form-control input-sm" ng-model="filterBy1[attobj.filterkey || attobj.key]" ng-model-options="{ updateOn: 'submit' }" placeholder="{{ attobj.name }}" ng-enter="cancel()" />
                  </div>
                </div>
                <input class="phoneSearchSubmitBtn" type="submit" value="submit" style="visibility:hidden;" />
              </form>       

</script>

The main controller, which includes the rendering of the mobileSearchPanel, contains functions for opening and closing the modal instance:

     $scope.showMobileSearchPanel = function (size) {
    //console.log($scope);
    var modalInstance = $modal.open({
      animation: true,
      templateUrl: 'mobileSearchPanel',
      // controller: 'listController',
      size: size,
      backdrop: true,
      scope: $scope
    });


      $scope.cancel = function(){
        modalInstance.close();
      };
   };

To enable the use of ng-enter directive, I have the following custom directive:

    // this allows to use on element that holds this directive the following.... ng-enter="myFunction()
app.directive('ngEnter', function () {
    return function (scope, element, attrs) {
        element.bind("keydown keypress", function (event) {
            if(event.which === 13) {
                scope.$apply(function (){
                    scope.$eval(attrs.ngEnter);
                });

                event.preventDefault();
            }
        });
    };
});

The current issue I'm facing is as follows:

-If I remove ng-enter="cancel()", the ng-model updates but I have to close and reopen the modal window each time I want to submit the form again.

-If I keep ng-enter="cancel()", the modal closes with the press of enter key but the submit functionality doesn't work.

I am looking for a solution where both the submit action and the modal closure can be triggered by pressing the enter key, or resolve any underlying issue causing the submit to only work once before requiring the modal to be closed and reopened for further searches.

This problem wouldn't occur if I didn't set "reloadOnSearch:true" in my route path, but I need this setting to ensure different search stages are reflected in the browser history. Removing this setting would resolve the issue at hand but jeopardize maintaining search history in the browser:

app.config(['$routeProvider', '$locationProvider', function($routeProvider, $locationProvider) {
  $routeProvider.
when("/list/:class", {controller: "listController", templateUrl: "DatabaseObject", reloadOnSearch: true}).

Answer №1

Is there a specific reason for utilizing ng-enter? Wouldn't it be more efficient to utilize ng-submit on the form instead?

<form name="search-form" ng-submit="doSearchThing()">

In addition, it might be beneficial to relocate the function responsible for closing the modal to the modal controller. This is evident as the modal already includes close and dismiss functions.

Furthermore, using 'cancel' in association with 'enter' appears semantically odd.

Answer №2

To resolve the issue, it is recommended to trigger the closing action of the modal when ng-change event occurs, which may not be detected until the enter key is pressed due to the use of ng-model-options:

    <script type="text/ng-template" id="mobileSearchPanel">


              <form name="search-form">
              <h1 style="text-align:center;">Search</h1>
                <div id="mobileSearcher">
                  <div ng-repeat="attobj in columns">
                    <input ng-if="attobj.filterable" type="text" class="form-control input-sm" ng-model="filterBy[attobj.filterkey || attobj.key]" ng-model-options="{ updateOn: 'submit'}" placeholder="{{ attobj.name }}" ng-change="closingModal()" />
                  </div>
                </div>
                <input class="phoneSearchSubmitBtn" type="submit" value="submit"  />
              </form>       


</script>

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

Pause execution of javascript function for a short period

When the button is clicked, my script executes the function manage($n) $onclick = "manage('$n');"; However, I also want to refresh the page immediately after it is clicked. $onclick="window.location.reload(true);manage('$n')"; Altho ...

Capture a screenshot of an embedded object and include it in an email using the mailto function

Is there a way to capture a screenshot of a flash object on a webpage and then send it via email using a mailto: form submission to a designated address? I have attempted to use different JavaScript techniques, but none seem to be successful. Appreciate a ...

Positioning a dropdown menu on top of a Google Map in React with JavaScript: Best Practices

I've been attempting to place a dropdown menu at a specific location on my Google Map, specifically in the top right (or top left is also acceptable). Below is the current output I am seeing: Here is the expected result: Modifications After trying ...

What is the optimal parameter order when utilizing pre-curried functions and composition in JavaScript?

We have a simple, mathematically curried function for subtracting numbers: function sub(x) { return function (y) { return x - y; }; }; sub(3)(2); // 1 The function signature matches the obtained result. However, when function composition comes i ...

Unable to access the .env file in Vue.js when executing cross-env NODE_ENV=development webpack-dev-server --open --hot

I'm attempting to utilize an .env file for storing local variables, but I am encountering an issue where they appear as undefined when I try to log them. Here is a snippet from my .env file (located at the root of my project): VUE_APP_STRAPI_HOST=htt ...

Tips for choosing a specific point on a Vuetify <v-slider> using Cypress

Currently, I am exploring how my application responds when a user interacts with a specific area on a basic Vuetify <v-slider>. How can I replicate this scenario in a Cypress integration test effectively? For instance, to click on the center of the ...

The async module has already been invoked with a callback function

Below is an array that I am working with: var files = [ { name: 'myfile.txt' }, { name: 'myfile2.txt' } ]; My goal is to access these objects asynchronously and send them for extraction, as shown below: Extraction function: ...

Placing the video at the center of the background image

                    Can someone assist me with a design issue I'm facing? I have two divs within a section. The left div contains a heading and a button, while the right div contains a video. However, when I try to add a background image to ...

Passing parameters to an external function in order to display a message is proving difficult. An error of type TypeError is being encountered, specifying that the Class constructor AlertMessage cannot be called without using the

Every time I attempt to pass a message as an argument to the showAlert() function, an error is triggered: Error: An instance of the AlertMessage class cannot be created without using 'new' image: I am simply trying to send the message as a para ...

What advantages can be gained from having multiple package.json files within a single application?

Embarking on the journey of creating my inaugural full react web application entirely from scratch. Previously, I've mainly worked on assignments that were partially pre-made for me. While setting up my project, I couldn't help but notice that I ...

Unselect all checkboxes except for the one that was clicked

In a project, I have 3 checkboxes that are interconnected and when one is clicked or checked, I want the others to be cleared while keeping the clicked checkbox checked. This behavior is similar to radio buttons but I cannot use radio buttons due to client ...

Using Three.js to extract Vertex Colors based on the z-coordinate of Vectors

Here is a sample: http://jsfiddle.net/c3shonu7/1/ The code demonstrates the creation of a BufferGeometry object by cloning an IcosahedronBufferGeometry's vertices. The goal is to apply a color gradient to the subdivided icosahedron, with lighter shad ...

React encountered a 400 error when attempting to call a function in node.js

While attempting to call a registration endpoint from a React front-end to a Node.js back-end using Axios, I encountered a 400 error: http://localhost:9000/user/register 400 (Bad Request) Here is my code: /* React component for user registration */ impo ...

Collaborating on React components across multiple projects while maintaining the central source code in one repository

I need a solution to effectively share React components, their Flow types, and SCSS between two projects while maintaining the source code in one project. The second project should only have read-only access to these components from the other project. Unf ...

Ways to share code across AngularJS frontend and Node.js backend

How can code be effectively shared between an AngularJS client and a Node.js server? After creating an AngularJS application, I now need to develop a RESTful server to provide data to the client. Some Angular services used on the client-side could also be ...

Passing parameters to JavaScript onload event from PHP

Looking for help with integrating date data from PHP into a JavaScript countdown function. I have extracted the date from a database using PHP, but struggling to pass it correctly to the JavaScript function. My attempt so far: <body onload="countIt(< ...

Using a JSON web token (JWT) for authorization on a json-server

I am currently working on developing a Node.js application that utilizes typicode json-server. My goal is to implement authorization within the app, where all public users have access to GET requests, but PUT, POST, and DELETE requests require a JWT token ...

Looking to retrieve the specific clientX and clientY JavaScript Position within a child div element on a Wordpress Page?

I've implemented a highlight hover map in JavaScript that displays an 'info box' div when hovering over a specific area at . However, I'm encountering an issue where the 'info box' doesn't appear precisely at the mouse lo ...

Explanation on subtracting the row value from a textbox

Click here to view the image For instance: If I enter a value in the "USED(kl)" textbox, it should subtract that value from the corresponding row where "KILOGRAM/S" is located; Upon clicking the update button, only the specific row should be affected wh ...

Struggling to locate images in Three.js

I'm facing a challenge with my Vue Cli app where I am attempting to use Three.js for rendering 3D objects within it. The issue arises when I attempt to load an image to utilize as a texture. let scene = new Three.Scene(); const spaceTexture = new Th ...