The ng-model is not properly syncing values bidirectionally within a modal window

I am dealing with some html

<body ng-controller="AppCtrl">
  <ion-side-menus>
    <ion-side-menu-content>
      <ion-nav-bar class="nav-title-slide-ios7 bar-positive">
        <ion-nav-back-button class="button-icon ion-arrow-left-c">
        </ion-nav-back-button>
      </ion-nav-bar>
      <ion-nav-buttons side="left">
        <button class="button button-icon button-clear ion-navicon" ng-click="toggleLeft()">
        </button>
      </ion-nav-buttons>

      <ion-nav-view animation="slide-left-right" name="main-view">
      </ion-nav-view>
    </ion-side-menu-content>
    <ion-side-menu side="left">
      <div class="list">
        <a menu-close href="#" class="item item-icon-left">
          <i class="icon ion-home">
          </i>
          Home
        </a>
        <a menu-close href="#/product" class="item item-icon-left">
          <i class="icon ion-home">
          </i>
          products
        </a>
        <a menu-close href="#/category" class="item item-icon-left">
          <i class="icon ion-home">
          </i>
          Category
        </a>

      </div>

    </ion-side-menu>
  </ion-side-menus>
  <script id="product.html" type="text/ng-template">
    <ion-view title="products">
      <ion-content>
      <div class="list">
        <a class="item" href="#/product-form?id={{item.id}}" ng-repeat="item in items | filter:{nome: searchText}">
          {
            {item.nome}
    }
      <span class="item-note">
        {
          {item.quantidade}
    }
  </span>
  </a>
  </div>    
  </ion-content>
    <div class="tabs tabs-icon-top">
      <a class="tab-item" href="#/product-form">
        <i class="icon ion-home"></i>
          Adicionar
  </a>
            <a class="tab-item" ng-click="openModal()">
              <i class="icon ion-search"></i>
                Filtrar
  </a>
  </div>     
  </ion-view>
  </div>
  </script>

  <script id="search.html" type="text/ng-template">
    <div class="bar bar-header item-input-inset">
      <label class="item-input-wrapper">
        <i class="icon ion-ios7-search placeholder-icon"></i>
          <input type="search" placeholder="busca" ng-model="searchText">
  </label>
            <button class="button button-clear" ng-click="closeModal()">
              cancelar
  </button>
  </div>
  </script>
</body>

Also, I am working with this controller

angular.module('ionicApp.controllers', ['ionicApp.config', 'xc.indexedDB'])
    .controller('ProductController',
        function ($scope, $ionicPopup, $timeout,
            $ionicModal, $indexedDB, $window, $ionicModal) {
            $scope.safeApply = function (fn) {
                var phase = this.$root.$$phase;
                if (phase == '$apply' || phase == '$digest') {
                    if (fn && (typeof (fn) === 'function')) {
                        fn();
                    }
                } else {
                    this.$apply(fn);
                }
            };

            var OBJECT_STORE_NAME = constants.productStore;
            $scope.items = [];
            $scope.searchText = "";

            $scope.getAll = function () {

                var myObjectStore = $indexedDB.objectStore(OBJECT_STORE_NAME);

                myObjectStore.getAll().then(function (results) {
                    // Update scope
                    $scope.safeApply(function () {
                        $scope.items = results;
                    });
                });
            };

            $scope.getAll();

            $ionicModal.fromTemplateUrl('search.html', {
                scope: $scope,
                animation: 'slide-left-right'
            }).then(function (modal) {
                $scope.modal = modal;
            });

            $scope.closeModal = function () {
                alert($scope.searchText);
                $scope.modal.hide();
            };

            $scope.openModal = function () {
                //$scope.searchText = "a";
                $scope.getAll();
                $scope.modal.show();
            };

            $scope.closeModal = function () {
                alert($scope.searchText);
                $scope.modal.hide();
            };
            //Cleanup the modal when we're done with it!
            $scope.$on('$destroy', function () {
                $scope.modal.remove();
            });
            // Execute action on hide modal
            $scope.$on('modal.hidden', function () {
                // Execute action
            });
            // Execute action on remove modal
            $scope.$on('modal.removed', function () {
                // Execute action
            });

        })

Update

This section defines the ProductController

var app = angular.module('ionicApp', ['ionic', 'ionicApp.controllers']);

app.config(function ($stateProvider, $urlRouterProvider) {
    $stateProvider
        .state('index', {
            url: "/",
            views: {
                'main-view': {
                    templateUrl: "home.html",
                    controller: "AppCtrl"
                }
            }
        })
        .state('product', {
            url: "/product",
            views: {
                'main-view': {
                    templateUrl: "product.html",
                    controller: 'ProductController'
                }
            }
        });

    $urlRouterProvider.otherwise("/");
});

The issue that I'm facing is that the searchText model isn't updating when the value changes. I have tried using $watch, ng-options.

In the openModal method, I can set an initial value to $scope.searchText, but after entering values, the model doesn't get updated, causing my list not to be filtered.

Can someone assist me with this?

Thank you.

Additional Note

I managed to solve the issue by adding the search text into the modal.

    $scope.modal = modal;
    $scope.modal.searchText = "";

And then I updated the attribute to the new variable.

<input type="search" placeholder="busca" ng-model="modal.searchText">

Thank you for the assistance.

Answer №1

For optimal performance, two-way binding is most effective when used with a nested object. Modify your bindings to utilize a structure similar to this:

$scope.info = {};
$scope.info.items = [];

Answer №2

The modal template is currently being loaded before it's actually in scope, which may be causing the issue.

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

What issue is present with this AJAX query?

Can you help me figure out where I went wrong with this AJAX code example that I'm trying to learn from? function loadXMLDoc() { var xmlhttp; if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new ...

Passing an event from a Vue3 parent component to its child component

How do I trigger a load event from a parent component to the child component? The child component needs to be able to listen for the load event in a slot-defined element and then perform some actions with the event. For example: <template> <slot ...

Is it possible to verify if a user is accessing a webpage through Electron?

If I were interested in creating a basic Electron application that notifies the user upon reaching example.com, is this achievable? If yes, then how can I determine if the user is on a particular webpage? ...

The process of incorporating injected JavaScript into an existing function

It seems like a classic issue, but I haven't been able to find the solution. I have a form that connects to a MySQL (actually MariaDB) database table called contacts. As part of the jQuery.ready() function, a drop-down list is populated through AJAX ...

Issue with Express.js res.append function: Headers cannot be set after they have already been sent

I encountered an issue in my express project where I tried to set multiple cookies using "res.append" in the same request, but I kept getting an error saying "Error: Can't set headers after they are sent.". Can someone help me identify the problem and ...

Converting a mongoDB response array from a JavaScript object to a JSON string: a step-by

After developing a custom javascript API to retrieve data from a MongoDB database, the issue arose where the data is being returned as an array of objects instead of a simple JSON string. The current statement used for retrieving the objects is: return db ...

Struggling to make the controller karma test pass

I am currently working on developing a "To Do list" using angular js. My goal is to allow users to click on a checkbox to mark tasks as completed after they have been finished. While the functionality works fine in the index.html file, I am struggling to p ...

What is the best way to pass a JSON object containing an array of objects to a Spring controller?

Currently, I have set up two domain models in Hibernate using @OneToMany mapping. My goal is to generate a JSON object on the frontend and then transmit it to the Spring MVC controller so that the model data can be automatically set. The main model classe ...

Error encountered: The call stack size has been exceeded due to the combination of Node JS, MongoDB, and Mongoose

I am facing a RangeError issue while attempting to create a new object using a predefined schema and inserting it into my mongodb database. I need assistance in debugging this error and finding a solution for it. Any help would be appreciated, thanks. App ...

How can I replicate the functionality of a div mimicking a select element using javascript upon clicking away from the element?

My task was to design a pseudo-select element that showcases columns for each row within the select. Due to HTML's restriction on allowing the <option> tag to include HTML, I had to find an alternate solution. One issue I encountered was replic ...

Neglecting specific packages in package-lock.json

Currently facing a perplexing dilemma with no clear solution in sight. In our ongoing project, we rely on npm for package management. Although we haven't been utilizing package-lock.json file lately, the need to reintroduce it has emerged. The issue ...

Encountering a MiniCssExtractPlugin error while trying to build with npm

I have encountered an issue while trying to execute "Npm Run Build" on my reactjs website. The error message I keep receiving is as follows: /usr/local/lib/node_modules/react-scripts/config/webpack.config.js:664 new MiniCssExtractPlugin({ ^ TypeErr ...

What is the best way to customize multiselection in jqgrid?

jQuery("#grid").jqGrid({ datatype: "local", width:'auto', height: 'auto', multiselect:true, colNames:[ 'no' ], colModel:[ {name:'no', align:'r ...

React: encountering issues with accessing component props after page refresh

Whenever I try to reload the 'details' page (not the homepage) on my app, I encounter the following error: "TypeError: Cannot destructure property 'flag' of 'country' as it is undefined." It seems that the data is ...

Checking if a phone number begins with a zero using a regular expression

Is there a way to ensure that numbers entered into a field always start with a 0? Initially, I thought the company wanted to mandate entering 0 first, but I believe there might be a more elegant solution. function validateNumber(dataValues, setErrors) ...

Loop through and write files using Node.js

I've been experimenting with a Google Trends API integration in node.js to gather data on the popularity of various search terms. My goal is to store a list of search words in an array, iterate through this array, call the Google Trends API for each ...

What are the steps to integrate dynamic data into chartjs?

Can you assist me in understanding how to dynamically populate Chartjs with data from a json file? Specifically, I am looking to dynamically fill the labels and data fields. Sample JSON File <<< [ { "EFICAZ_TAB_ITEM_ID":1, " ...

Incapable of composing text using the MUI SearchBar

I'm having trouble with my Material UI search bar - it's not letting me type anything into it. How can I resolve this issue? Despite trying the suggested code snippets from other answers, I keep encountering errors when integrating them into my ...

Utilizing server-side variables with JavaScript in Node.js, Express.js, and EJS

Hello everyone, I am just getting started with backend programming and I'm currently working on a project where I need to send an array of objects to the client. My goal is for the client to then add an object to this array. I am using node.js in conj ...

Exporting a function from one module does not automatically make it accessible in another module

I'm stuck trying to call the retrieve_endpoints function from cli_config.js. I made sure to add the functions to the module exports and included the require statement in the cli_config file. But for some reason, I can't seem to access the retriev ...