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

Having trouble launching Cypress on my Mac - stating that it cannot find Cypress

Despite searching through multiple answers on S.O, none of them have solved my issue. To better explain my question, I've created a video. You can view it here Everything was working perfectly just yesterday, so what could have possibly gone wrong? ...

What is the best way to access the element menu with element-ui?

I am looking for a way to programmatically open an element in my menu, but I haven't been able to find any information on how to do it. HTML <script src="//unpkg.com/vue/dist/vue.js"></script> <script src="//unpkg.com/<a hr ...

Strange behavior observed when transclusion is used without cloning

During my experimentation with transclusion, I wanted to test whether the transcluded directive could successfully locate its required parent directive controller after being transcluded under it. The directives used in this experiment are as follows: - Th ...

Watch for changes in a nested collection in Angular using $scope.$watch

Within my Angular application, there is a checkbox list that is dynamically generated using nested ng-repeat loops. Here is an example of the code: <div ng-repeat="type in boundaryPartners"> <div class="row"> <div class="col-xs- ...

Direction of Scrolling

Is it possible to have a div move in the opposite direction of mouse scroll, from the top right corner to the bottom left corner? Currently, it is moving from the bottom left to the top right. #block { position: absolute; top: 400px; left: 100px; < ...

Copy password input field content in Vue to clipboard

I'm currently working on a Vue app that includes a form input for creating passwords. I've managed to implement a button that shows/hides the password, but I'm struggling with adding a copy to clipboard function. It doesn't seem to be w ...

What is the best way to obtain the current route name within a Component?

Is it possible to retrieve the current route name in a controller? I have attempted using this.route, this.currentRoute, and this._routerRoot, but none of them seem to work. computed: { currentRoute:{ get(){ console.log(this.__routerRoo ...

Defer the rendering of Vue.js pages until the data request is completed

I am currently working on a page that retrieves data from the server using axios. My goal is to wait for the axios request to complete before rendering the page content. The reason behind this approach is that I already have a prerendered version of the ...

Deviations in Scriptaculous Callbacks during Movement Effects

I am looking to create a dynamic menu item that moves out 5px on mouseover and returns to its original position using Scriptaculous. I have implemented the afterFinish callback to ensure that the bump-out effect is completed before the item moves back in. ...

Experiencing an unexpected wait before the requestAnimationFrame?

Surprisingly, Internet Explorer is actually performing the way I want it to in this case :-) I developed a function for SVG animations using requestAnimationFrame (for simplicity, I left out the value calculations here ... but my initial test involved an ...

Creating a Commitment - Resolving the "Expected ')' after argument list" Error

Can someone please help me locate the syntax error in this code snippet? I've been searching for ages! An error occurred: Uncaught SyntaxError: missing ) after argument list promiseArray.push( new Promise(function (resolve, reject) { ...

What You See Is What You Get - A versatile tool for editing both text and

As a developer, I have encountered a common need that StackOverflow addresses. Situation I am in the process of creating a website where users can post code examples and articles using an admin system. These posts may be created by me or registered fron ...

How can we stop the jumping of images in the grid? Is there a way to eliminate the jump effect?

Here is a script I am working with: <script src="http://static.tumblr.com/mviqmwg/XyYn59y3a/jquery.photoset-grid.min.js"></script> <script> $(document).ready(function() { $('.photoset-grid').photose ...

Adding auth0 authentication to a Next.js 13 application: A step-by-step guide

Currently, I am using a nextjs 12 application and set up auth0 as my authentication provider by following the guidelines provided here: https://auth0.com/docs/quickstart/webapp/nextjs/interactive. However, I am now looking to upgrade my application to next ...

Is it possible for Vue to retrieve refs on mounted during nextTick following the dynamic import of the component?

Utilizing Nuxt js and Element UI, I have dynamically imported Element UI plugins in the plugins folder. export default () => { Vue.component("ElForm", () => import("element-ui/lib/form")); Vue.component("ElFormItem", ...

Paging in Ext JS does not function properly when using local data sources

I am facing an issue with enabling paging in ExtJs4 grid. The paging toolbar appears to be functioning correctly, however, the paging feature does not seem to work within the grid itself. Can anyone provide guidance on what might be missing? Ext.onReady(f ...

The absence of essential DOM types in a TypeScript project is causing issues

Recently, I've been working on setting up a web app in TypeScript but I seem to be missing some essential types that are required. Every time I compile using npm run build, it keeps throwing errors like: Error TS2304: Cannot find name 'HTMLEleme ...

Developing a react native library (create-react-native-library) incorporating a distinct react-native version within its designated Example directory

I'm looking to develop a React Native library, but the testing folder (example folder) it contains the latest version of React Native. However, I specifically need version 0.72.6 in the example folder. Is there a command for this? Current command: np ...

Any suggestions on resolving the message "Unable to locate module './commands/${file}'"?

Can someone assist me in resolving this issue? I am trying to develop a code that includes advanced commands. Here is the code snippet: const commandFiles = fs.readdirSync('./commands/').filter(file => file.endsWith('.js&apo ...

Creating a customized SelectField component for Material-UI v1.0.0-alpha.21 with a fix for the Menu anchorEl problem

Currently, Material-UI v1.0.0 does not have a selectField implemented yet so I am attempting to create my own version using TextField, Menu, and MenuItem Components. Below is the code for my custom selectField: export default class SelectField extends Rea ...