Update input field value with data retrieved via ajax call in AngularJS

My current approach involves using AngularJS directives for Bootstrap in order to create an edit form on a Bootstrap modal when the user clicks on the edit button from a list of items. Here is the code I have implemented:

HTML:

<div class="modal-header">
            <h3>Edit Template</h3>
        </div>
        <div class="modal-body">
            <form name="form" class="form-horizontal" novalidate>
                <fieldset>
                    <div class="span4" ng-class="smClass" ng-show="etemplate.status">{{etemplate.status}}</div>
                    <div class="control-group">
                        <label class="control-label" for="etemplateName">Name</label>
                        <div class="controls">
                            <input class="input-xlarge" id="etemplateName" ng-model="eTemplate.name" maxlength="150" type="text" required />
                        </div>
                    </div>
                    <div class="control-group">
                        <label class="control-label" for="etemplateDesc">Description</label>
                        <div class="controls">
                            <textarea id="templateDesc" id="etemplateDesc" ng-model="eTemplate.desc"></textarea>
                        </div>
                    </div>
                    <div class="center">
                      <input type="text" style="display:none;" ng-model="eTemplate.id" value="{{eTemplate.id}}" required />
                      <button type="button" ng-click="update(eTemplate)" class="btn btn-primary" ng-disabled="form.$invalid || isUnchanged(eTemplate)">Submit</button>
                      <button class="btn" ng-click="cancel()">Cancel</button>
                    </div>
                </fieldset>
            </form>
        </div>

Controller:

controller('TemplateController', ['$scope', '$http', '$modal', function($scope, $http, $modal) {
    var tmpId = '';
    $scope.openEdit = function(id) {
        tmpId = id;
        var editTmpModalInstance = $modal.open({
            templateUrl: 'editTemplateContent.html',
            controller: 'ETModalInstance'
        });

        $http({
            method: 'GET',
            url: adminBaseUrl+'/get_template/',
            params: {'id': tmpId}
            }).
            success(function(data, status, headers, config) {
                $scope.$broadcast('EditTemplateDataReached', data);
            }).
            error(function(data, status, headers, config) {
            });
    }
}]).

controller('ETModalInstance', ['$scope', '$http', '$modalInstance', function($scope, $http, $modalInstance) {
    $scope.emaster = {};
    $scope.smClass = '';
    $scope.eTemplate = {};

    $scope.$on('EditTemplateDataReached', function(data) {
        $scope.eTemplate = data;
        $scope.$apply();
    });

    $scope.isUnchanged = function(eTemplate) {
        return angular.equals(eTemplate, $scope.master);
    };

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

    $scope.update = function(eTemplate) {
        var strng = $.param(eTemplate);
    };
}]).

When a user clicks on the edit button, the ID of the selected item is passed to the controller which then sends an AJAX request to the server to populate the fields with the respective values. However, I am facing an issue where the fields do not get populated when the AJAX data is returned.

Answer №1

Identified the issue in my code where I mistakenly used $scope for broadcasting and catching data when I should have used $rootScope instead.

Incorrect Implementation:

$scope.$broadcast('EditTemplateDataReached', data);
$scope.$on('EditTemplateDataReached', function(data) {
        $scope.eTemplate = data;
        $scope.$apply();
    });

Correct Implementation:

$rootScope.$broadcast('EditTemplateDataReached', data);
$rootScope.$on('EditTemplateDataReached', function(e, data) {
        $scope.eTemplate = data;
        $scope.$apply();
    });

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 with Node.js GET request functionality not functioning properly

I've been encountering difficulties with loading a page using Node.js. While my Node.js Application code functions properly when attempting to load other resources such as www.google.com, it seems to encounter issues specific to the domain name www.eg ...

What is the best way to add selected values from a multi-select dropdown into an array?

Attempting to populate an array from a multiple select dropdown, I've encountered an issue. Despite using splice to set the order of values being pushed into the array, they end up in a different order based on the selection in the dropdown. For insta ...

Creating Browser Extensions with Vue.js and Vue CLI

I am in the process of creating a Chrome Extension with a frontend powered by Vue.js. Everything was going smoothly using vuecli until my app started utilizing the Webextension-API. This API is only accessible to registered Extensions, not normal websites. ...

The Node.js application that uses Express and connects to a MSSQL database is reporting that the database

One of my other applications utilizes express and routes, but for this new app I wanted to simplify it. Despite being confident in the correctness of the connection string, I encountered an issue. script.getQuestions(connection); script.getQuestions = fu ...

Combining AngularJS with ng file upload and Sails JS for seamless file uploading

When I upload a file, I also need to send some additional information along with it. The instructions mention using the data parameter for this purpose, but I'm having trouble accessing it in my Sails controller action. Frontend: Upload.upload({ url ...

How can I access my API by connecting Node.js to MongoDB remotely?

I have been working on developing an application using Node.js, Express, and MongoDB. I followed some teamtreehouse tutorials to set up Node.js and MongoDB on a Digital Ocean Server. However, when trying to access my API through various URL variations, I e ...

Altering the href text within a script causes the text to disappear instead of updating

Function Triggered by Button Click: function LoadEnglishText() { document.getElementById("txt_whatwedo_learnmore2").innerHTML = "here."; } HTML Link to be Updated: <a id="txt_whatwedo_learnmore2" href="./pdf/Pricing_App_Dev_2019_Ger.pdf">hier ...

Obtaining the client's IP address using socket.io 2.0.3: a comprehensive guide

Currently, I am facing a challenge using socket.io v2.0.3 in my node.js server as I am unable to retrieve the client's IP address. Although there are several suggestions and techniques on platforms like stackoverflow, most of them are outdated and no ...

Checking phone number on a React.js form

I am currently working on a front-end application and need to implement form validation. I am relatively new to ReactJS and learning as I go along in the development process. One of the input fields requires a phone number, which should only accept number ...

How can JavaScript be utilized to disable the use of the spacebar?

I have implemented a live search feature on the website I'm working on. Currently, the search function queries the MySql database as soon as the first character is entered and updates the results with each subsequent character input. However, I'v ...

Converting JavaScript code into PHP syntax

I'm curious about code organization. The original code in this snippet is functioning properly: <?php if (isset($_POST['submit'])){ ... ... $invalidField = 2; } ?> <!DOCTYPE html PUBLIC "-//W3C//DTD ...

Need help fixing my issue with the try-catch functionality in my calculator program

Can someone assist me with my Vue.js calculator issue? I am facing a problem where the output gets added to the expression after using try and catch. How can I ensure that both ERR and the output are displayed in the {{output}} section? Any help would be a ...

Tips on sending nested JSON data to a Spring Controller

My JSON structure looks like this: "Organization":{ "legalname" : "", "dba" : "", "fein" : "" } In my Jquery code, I make an AJAX call like this: $.ajax({ type: "POST", con ...

Initiate automatic playback of audio on website following a delay

I attempted to change the state of play from false to true and also experimented with adding ComponentDidMount,ComponentDidUpdate, and ComponentWillMount but unfortunately, nothing seemed to solve the issue. I consistently encountered errors at different p ...

Ensure that the second ajax call retrieves the first result every time

This is the code snippet I am currently using: <script type="text/javascript> $(function() { $('#DoTask').click(function(event) { event.preventDefault(); // added this $.getJSON('/TareasBackGround/DoTaskInteractivo ...

Switch to admin view after successful login within the angularjs application

My application uses MVC with Node.js and AngularJS on the frontend. The login page has a different top menu compared to other pages. How can I switch between these headers to display in the view? In the AngularJS login controller, I call a service that ch ...

The process of locating a textarea by its id becomes obsolete when integrating CKEDITOR

The data table has editable cells, where clicking on a cell will trigger a bootstrap modal to display with a textarea containing the text retrieved from the database. Snippet of the table structure: <table class="table table-striped table-hover" id="t ...

Drop and drag to complete the missing pieces

Here is a drag and drop fill in the blanks code I created. The challenge I'm facing is that I want users to be able to correct their mistakes by moving words to the right place after receiving points. <!DOCTYPE HTML> <html> <head&g ...

Issues arise with routing when specific route parameters are implemented

After setting a route parameter in my browser URL, I encountered errors with the routing of the public folder (which contains my CSS, JS, etc.). The app's structure is as follows: app | |-- public | └-- css | └-- profile.css | |-- ...

Having trouble replacing scss variables in react-h5-audio-player

I recently integrated react-h5-audio-player into my project and followed the instructions on the README page to customize the styles by updating the SCSS variables that control the colors. However, it appears that my custom styles are not being applied. An ...