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

How to retrieve the path, route, or namespace of the current or parent component/view in a Vue.js application

I have been working on enhancing a sub-menu system for vue.js that dynamically populates based on the children routes of the current route. I recently asked a question about this and received a helpful answer. Currently, I am trying to further improve the ...

Running into strictdi error for a controller that utilizes $inject syntax

After enabling strict-di on my application for minification purposes, I am facing strictdi errors and working on resolving them. One of the controllers is throwing a strictdi error even though I am correctly annotating using $inject following the John Papa ...

Storing blank information into a Mongodb database with Node.js and HTML

Can someone please assist me with solving this problem? const express=require("express"); const app=express(); const bodyparser=require("body-parser"); const cors=require("cors"); const mongoose=require("mongoose"); ...

Exploring and modifying Angular objects using the Chrome console

While reviewing an Angular webpage, I came across an object named vm. Attempting to inspect it using console.log(vm) resulted in the following error: Uncaught ReferenceError: vm is not defined(…) Is there a different way for me to inspect this object? ...

AngularJS: The dynamic setting for the stylesheet link tag initiates the request prematurely

I'm encountering a problem that is somewhat similar (although not exactly the same, so please be patient) to the one discussed in Conditionally-rendering css in html head I am dynamically loading a stylesheet using a scope variable defined at the sta ...

Modifying the user interface (UI) through the storage of data in a class variable has proven to be

If I need to update my UI, I can directly pass the data like this: Using HTML Template <li *ngFor="let post of posts; let i = index;"> {{i+1}}) {{post.name}} <button (click)="editCategory(post)" class="btn btn-danger btn-sm">Edit</butto ...

Chrome reports a Javascript error: indicating that it is not recognizing the function

When working with a js file and html, I encountered an issue where one function works fine but another prompts an error in Chrome: Uncaught TypeError: specification_existing is not a function I'm puzzled as to why one function works while the othe ...

When a block reaches a certain height, the mat-chip-list in Angular Material is automatically shortened to fit. This feature is exclusive to

<div fxFlex="100" fxFlex.gt-sm="80" fxFlex.sm="100"> <div *ngFor="let permission of arrayOfObjectPermissions; let index = z" class="permissions-list"> <mat-card [title]=&qu ...

Can the caller function's arguments be altered using Function.prototype.apply()?

function modifyValues(a,b){ console.log(arguments); //["oldValue","oldValue"] var newArguments = updateValues.apply(this,arguments); for (var i=0;i<arguments.length;i++){ arguments[i] = newArguments[i]; } console.log(arguments); // ...

Exploring smooth scrolling functionality using AngularJS and integrating it with IFrames

After implementing an angular controller, I included the following code: angular.element(document).ready(function () { ... } Within this setup, I added a function to enable smooth scrolling to the hash of window.location.hash using .animate({scrollTop... ...

What could be causing the incorrect updating of React State when passing my function to useState?

Currently, I am in the process of implementing a feature to toggle checkboxes and have encountered two inquiries. I have a checkbox component as well as a parent component responsible for managing the checkboxes' behavior. The issue arises when utiliz ...

Ways to stop jQuery from stripping the <script> elements

Is there a way to stop jquery from removing my JS default behavior? function loadPageSuccess(data) { var data = $(data).find('#content'); alert($(data).html()); $("#content").html(data); $("#page").fadeTo(100,1); } function loadP ...

url-resettable form

Currently, I am working on an HTML form that includes selectable values. My goal is to have the page load a specific URL when a value is selected while also resetting the form back to its default state (highlighting the "selected" code). Individually, I c ...

What are the steps for setting up jScroll?

As a newcomer to JS & jQuery, I appreciate your patience. I've been working on creating a dynamic <ul> list using JS, and I'm happy that it's finally coming together. Now, my next step is to incorporate infinite scrolling into my ...

Tips for passing a URL variable into an Ajax script to prefill a form input in a search field

I have a website with a search feature that dynamically queries a database as you type in the search field, similar to Google's search suggestions. This functionality is achieved through AJAX. As the results appear on the page while you enter your se ...

Creating a function within a module that takes in a relative file path in NodeJs

Currently, I am working on creating a function similar to NodeJS require. With this function, you can call require("./your-file") and the file ./your-file will be understood as a sibling of the calling module, eliminating the need to specify the full path. ...

What could be causing this test to fail when testing my API endpoint?

Why am I encountering this error? Uncaught exception: Error: listen EADDRINUSE: address already in use :::3000 import supertest from "supertest" import axios from "axios" import app from ".." const request = supertest(app ...

Display a persistent bar on the page until the user reaches a specified <div> element through scrolling

Looking to implement a sticky bar at the bottom of my page that fades out once the user scrolls to a specific div and then fades back in when scrolling up and the div is out of view. This bar should only appear if the user's screen size is not large ...

Is there a way to use JavaScript to choose options within a <select> element without deselecting options that are disabled?

Here's the code snippet I am working with at the moment: <select id="idsite" name="sites-list" size="10" multiple style="width:100px;"> <option value="1" disabled>SITE</option> ...

Importing TypeScript Modules from a Custom Path without Using Relative Paths

If we consider the following directory structure: - functions - functionOne - tsconfig.json - index.ts - package.json - node_modules - layers - layerOne - tsonfig.json - index.ts - index.js (compiled index.ts ...