Having trouble retrieving input data from a modal pop up with Angular.js

I am facing an issue with my modal pop up form in Angular.js. I am unable to retrieve the form data using ng-model. Below is the code snippet:

<modal title="Owner Information" visible="showModal">
  <form class="ng-pristine ng-valid" id="frmsignup" name="frmsignup" autocomplete="off">
  <div class="input-group bmargindiv1 col-lg-4 col-md-4 col-sm-4 col-xs-12 plr-15">
        <span class="input-group-addon ndrftextwidth text-left">Status:</span>
            <select class="form-control" name="status" id="status" ng-model="status" required="required">
            <option value="">Select Status</option>
            <option value="1">Active</option>
            <option value="0">Inactive</option>
            </select>
  </div>
<div class="input-group bmargindiv1 col-lg-4 col-md-4 col-sm-4 col-xs-12 plr-15">
        <span class="input-group-addon ndrftextwidth text-left">Comment:</span>
            <textarea rows="5" cols="50" class="form-control" id="comment" name="comment" ng-model="comment" required="required">
            </textarea>
    </div>
  <input type="button" class="btn btn-success" ng-click="updateOwnerData();" id="addProfileData" value="Save" />
</form>
</modal>

Here is a glimpse of my modal pop up:

var dept=angular.module('cab');
dept.controller('ownerviewController',function($scope,$http,$timeout,$state,Upload,$window,DataService){
   $scope.updateOwnerData=function(){
          console.log('data',$scope.status,$scope.comment);
   }
})
dept.directive('modal', function () {
    return {
      template: '<div class="modal fade">' + 
          '<div class="modal-dialog modal-lg">' + 
            '<div class="modal-content">' + 
              '<div class="modal-header">' + 
                '<button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>' + 
                '<h4 class="modal-title">{{ title }}</h4>' + 
              '</div>' + 
              '<div class="modal-body" ng-transclude></div>' + 
            '</div>' + 
          '</div>' + 
        '</div>',
      restrict: 'E',
      transclude: true,
      replace:true,
      scope:true,
      link: function postLink(scope, element, attrs) {
        scope.title = attrs.title;

        scope.$watch(attrs.visible, function(value){
          if(value == true)
            $(element).modal('show');
          else
            $(element).modal('hide');
        });

        $(element).on('shown.bs.modal', function(){
          scope.$apply(function(){
            scope.$parent[attrs.visible] = true;
          });
        });

        $(element).on('hidden.bs.modal', function(){
          scope.$apply(function(){
            scope.$parent[attrs.visible] = false;
          });
        });
      }
    };
  });

The above script part highlights my problem - I cannot fetch values through $scope from the popup window. My goal is to capture these values via Angular.js Scope.

Answer №1

I struggled to identify the issue with scopes. It appears that values are confined within (allowing you to set the initial value for ng-model), but they do not leak outside. Therefore, I opted for utilizing the controllerAs syntax and adhered to the view model principle:

dept.controller('ownerviewController',function($scope){

    var vm = this; // Introducing the view model

    $scope.openPopUP=function(){
        $scope.showModal = !$scope.showModal;
    }
    $scope.updateOwnerData=function(){
        console.log('data', vm.status, vm.comment); //Displaying data from the view model
    } 
})

The next step would involve defining the view model in your template using the controllerAs syntax and updating ng-model bindings:

<body ng-controller="ownerviewController as vm">
...
   <select class="form-control" name="status" id="status" ng-model="vm.status" required="required">
   ...

You can access the functional example here

The complete version featuring a modal popup is also accessible here

Answer №2

Understanding Scopes in Directives

When working with the modal pop-up directive, it's important to note that both transcluded: true and scope: true create their own isolated scopes. However, if you want to access and update inputs from your controller's scope, you'll need to take another approach.

To learn more about this concept, check out the visual explanation provided in this resource.

Effective Communication with Parent Scope

If you need to communicate effectively with your parent's scope from within a directive or transcluded-form, consider the following techniques:

  • Include an individual scope parameter { status: '=', comment: '=' } in your directive, using two-way binding '=' to pass the parent's scope variables like so:
    <modal title="Owner Information" visible="showModal" data-status="status", data-comment="comment">
  • Create and integrate a factory or service to manage communication, such as updating data, between the directive (form) and controller

For additional insights on this topic, refer to the discussion linked here: AngularJS : Directive transcluded scope lost

An Innovative Solution Using Inherited Scope

For a practical demonstration of utilizing inherited scopes, take a look at this live example. By leveraging prototypical inheritance from the parent scope (controller), you can seamlessly utilize the model (e.g., status, comment) and execute functions within the transcluded form.

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

Building a dynamic cities dropdown menu in ReactJs based on the chosen country

I have an array called countryList that looks like this: export const countryList = [ {name: 'Singapore', code: 'SG', cities:[ "Ang Mo Kio New Town", "Ayer Raja New Town", ...

Instead of presenting MySQL data in tables on an HTML page, showcase it in editable text boxes

I have successfully imported data from my database table into an HTML table, but now I want to display them in locked text boxes. When the user clicks an "edit" button, the corresponding text box should become unlocked so that they can edit the data and sa ...

What is the most effective method for storing multiple data points in an array?

I have developed the following script: let data = [ {day: 1, time: '08:00', note: 'madrid'}, {day: 2, time: '08:00', note: 'barcelona'}, {day: 3, time: '10:00', note: 'juve ...

Dynamic blog posts experiencing issues with syntax highlighting feature

I am currently developing a blog using Vue and have decided to incorporate syntax highlighting for the code snippets in my posts by utilizing vue-highlightjs. In order to write the content of my blog posts, I am simply using a textarea within my admin pane ...

How can I generate an HTML table by making JavaScript AJAX requests in a structured manner?

I'm new to JavaScript and currently working on dynamically creating a table. I've encountered an issue with the order of execution in my code. I understand that JavaScript doesn't execute sequentially, so I'm looking for a workaround. ...

Error Message: SCRIPT5 - Permission Denied When Trying to Open PDF with Javascript

Despite searching through multiple posts on SO, I have yet to find a solution to my issue. We operate a web form within our LAN that utilizes Javascript's OPEN function to open PDF files. Up until recently, everything was working smoothly. However, ...

Having trouble interpreting JSON with Jquery

I am attempting to implement autosuggestion using Solr in conjunction with jQuery. Below is the code I have written for this purpose: $(function() { $( "#artist" ).autocomplete({ source: function( request, response ) { $.ajax({ ...

What steps can be taken to enhance cleanliness and efficiency, and what are some recommended practices to adhere to?

Currently, I am in the process of developing a user authentication system on the backend. Specifically, I have implemented a POST method for registering new users. userRouter.post("/", expressAsyncHandler(async (req, res) => { try { const { na ...

Isotope: Real-time JSON content extracted from Google Spreadsheet

My goal is to populate an Isotope list using data from a Google Spreadsheet JSON. However, I'm facing issues with the animation and sorting functionality once I add the JSON. Although I have verified that the JSON/JavaScript for loading it works, I am ...

What is the most effective approach for annotating TypeScript abstract classes that are dynamically loaded?

I am in the process of developing a library that allows for the integration of external implementations, and I am exploring the optimal approach to defining types for these implementations. Illustration abstract class Creature { public abstract makeN ...

Add three rows without clicking, then click once to add one row at a time

Seeking guidance on how to defaultly display 3 rows after adding and removing rows, as well as applying the removal of a default set of 3 rows using JavaScript. Any valuable ideas are appreciated! Example needed:- https://i.sstatic.net/DF8Wn.png $(docum ...

Effective method for JSON data parsing

Greetings everyone, I have a question regarding performance implications in JavaScript. I have a JSON query result as follows: [{'name': 'a'}, {'name': 'b'}] For another query, I need to manipulate it to the foll ...

What is the best way to access data from outside a forEach loop in JavaScript?

I am trying to access the value of my uid outside of the foreach loop in my code. Can anyone assist me with this? This is the code I am working with: var conf_url = "https://192.168.236.33/confbridge_participants/conference_participants.json?cid=009000 ...

React Resize Detection: Handling Window Resize Events

Is there a more efficient way to listen for the window resize event in react.js without causing multiple callbacks? Perhaps a React-oriented approach (like using a hook) to achieve this? const resizeQuery = () => { console.log("check"); if ( ...

How to redirect in Next.js from uppercase to lowercase url

I'm trying to redirect visitors from /Contact to /contact. However, following the instructions in the documentation results in an endless loop of redirects. This is my attempted solution: // next.config.js async redirects() { return [ { ...

Tips for triggering the JavaScript function within dynamically created textboxes on an ASP .NET platform

I have developed code that dynamically creates textboxes in a modal pop-up each time the add button is clicked and removes them when the remove button is clicked. The validation function in this code checks for valid month, date, and year entries in the te ...

Working with session variables in combination with Javascript and the UpdatePanel control can greatly enhance the

During a button click event, I am saving values in session and invoking JavaScript from the code behind. However, I am facing difficulties accessing these session values in JavaScript due to my use of an update panel. Can someone provide a suitable solut ...

What are some alternative ways to redirect multiple pages in a Navbar component in React Js without encountering the 'useNavigate()' error?

How can I resolve this error while working with react js? Error: useNavigate() is only allowed within a <Router> component. ▶ 3 stack frames were collapsed. Navbar C:/Users/dell/OneDrive/Desktop/ReactJs/react-learning/src/components/Navbar.js:9 ...

Accessing files from various directories within my project

I'm working on a project with 2 sources and I need to import a file from MyProject into nest-project-payment. Can you please guide me on how to do this? Here is the current file structure of my project: https://i.stack.imgur.com/KGKnp.png I attempt ...

Combining Array Elements to Create Overlapping Images in JavaScript

My goal is to create a planner where users can choose a wallpaper based on the season. Right now, I'm focusing on fall, and when you click on fall, you can see all the different wallpapers (each URL from my array is displayed). However, once the alert ...