The ng-model directive in Angular is effective for handling arrays, however, it may not

The implementation of the ng-model directive seems to be incomplete when dealing with string values in JavaScript. However, by using a list of dictionary objects and looping through them with ng-repeat, this issue is resolved.

One reason for this behavior could be that returning an array functions as a reference to the object, while returning a string variable simply returns the literal string. This might be interfering with Angular's two-way data binding, resulting in the variable holding a value of undefined.

Why is my service module below unable to retrieve the updated value from the view for the variable gitRelease?

In a service module, the following functionality is present:

(function () { //start iife

    'use strict';

    angular.module('gms.autoDeploy')
        .factory('AutoDeployService', ["$http", "$q", "$log", "$cookies", "APP_CONFIGS", "SweetAlert", "$timeout", "GridSettingsService", "APP_USER", AutoDeployService]);

    function AutoDeployService($http, $q, $log, $cookies, APP_CONFIGS, $timeout, SweetAlert, GridSettingsService, APP_USER) {

        var tibcoCopyJobs = [];
        var gitRelease = "";

        function addNewTibcoCopyJob() {
            tibcoCopyJobs.push({
                sourceServer: "",
                sourcePath: "",
                destinationServer: "",
                destinationPath: ""
            });
        }

        function getTibcoCopyJobs() { return tibcoCopyJobs; }
        function getGitRelease(){ return gitRelease; }

        function extractFormData() {
            console.log(gitRelease);
            for (var i = 0; i < tibcoCopyJobs.length; i++) {
                console.log(tibcoCopyJobs[i]);
            }
        }

        return {
            addNewTibcoCopyJob:             addNewTibcoCopyJob,
            getTibcoCopyJobs:               getTibcoCopyJobs,
            getGitRelease:                  getGitRelease,
            extractFormData:                extractFormData
        };
    } //end AutoDeployService
}()); //end iife

Utilizing it in conjunction with this controller:

angular.module("gms.autoDeploy").controller('AutoDeployController', ['$scope', '$compile', 'AutoDeployService',
function ($scope, $compile, AutoDeployService) {

        var model = this;

        init();

        function init() {
            model.tibcoCopyJobs = AutoDeployService.getTibcoCopyJobs();
            model.gitRelease = AutoDeployService.getGitRelease();
        }

        function btn_addNewTibcoCopy() { AutoDeployService.addNewTibcoCopyJob(); }

        function btn_extractFormData() { AutoDeployService.extractFormData(); }

        model.btn_addNewTibcoCopy = btn_addNewTibcoCopy;
        model.btn_extractFormData = btn_extractFormData;
    }
]);

To facilitate this view:

<div ng-controller="AutoDeployController as autoDeploy">
<div class="container-fluid">

<div class="row">
    <div class="col-md-2">
        <input type="text" class="form-control" ng-model="autoDeploy.gitRelease" placeholder="MM-DD-YYYY">
    </div>
</div>

<div class="row">
    <fieldset class="col-md-2" style="margin-bottom: 10px" ng-repeat="item in autoDeploy.tibcoCopyJobs track by $index">
        <legend>Copy</legend>

        <input type="text" class="form-control" placeholder="Source Server..." ng-model="item.sourceServer">
        <br/>
        <input type="text" class="form-control" placeholder="Source Path..." ng-model="item.sourcePath">
        <br/>
        <input type="text" class="form-control" placeholder="Destination Server..." ng-model="item.destinationServer">
        <br/>
        <input type="text" class="form-control" placeholder="Destination Path..." ng-model="item.destinationPath">
    </fieldset>
</div>

<button ng-click="autoDeploy.btn_extractFormData()">extract</button>
<button ng-click="autoDeploy.btn_addNewTibcoCopy()">TIBCO copy</button>
</div>
</div>

Answer №1

Explaining why arrays are returned by reference while strings are copied by value can help clarify your question. Let me provide a more detailed explanation.

When you write

model.gitRelease = AutoDeployService.getGitRelease();

the model object will create the getRelease property like this:

{getRelease: "", ... (more properties from the controller)}

Any updates in the view will only affect the getRelease property in the controller.

To solve this issue, you can follow Jags' suggestion mentioned in the comments. Another option is to create a reference to your service in the controller:

var model = this;
model.autoDeployService = AutoDeployService;

In your view, use the following code:

<input type="text" class="form-control" ng-model="autoDeploy.autoDeployService.gitRelease" placeholder="MM-DD-YYYY">

This should resolve the problem.

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

Is it possible to launch a browser window using javascript?

I need to open a new Internet Explorer browser window and I am currently using the following code: window.open("http://jsc.simfatic-solutions.com", "mywindow"); However, I would like to know how can I open a new IE window with a fresh session? ...

Is there a way for me to confirm that I am receiving the 401 error when fetching data?

When using an async function to fetch data, how can one determine if a 401 error occurred during the data retrieval process? The code example is as follows: async function getBilling(url, id, date) { let header = { method: 'GE ...

CSS modified after opening a modal dialog that has loaded external HTML content

Within my ASP.NET MVC project, I am utilizing a tab wizard. On one of the tabs, I trigger a modal dialog by loading HTML content from an external API. However, once I close the wizard and navigate to the next tab, the table style (specifically border color ...

Sending a parameter to the load method of the Selectize jQuery extension

I have a question about using the Selectize jQuery plugin for a dropdown box. I am not very familiar with jQuery, so please bear with me if this is a simple issue. I am making an ajax call to fetch data for the dropdown, but I need to pass a variable to th ...

Adjust the jQuery and PHP script to retrieve both the ID and text content to populate an OPTION element

I have a basic DROPDOWN list: <select class='form-control' id='builders' name='builder_id'> <option value="1">Java</option> <option value="2">Python</option> </select> I am looking ...

Set all form fields to ng-touched programmatically when the form is submitted

HTML: <div class="form-group" ng-class="{ 'has-error' : form.firstName.$invalid && form.firstName.$touched }"> <label for="firstName" class="control-label"> First Name </label> <input t ...

When there is an absence of data, the jQuery datatable mysteriously van

I have encountered an issue in my Django app where a datatable used in the template disappears if there is missing data in any column or row. The problem occurs when trying to download the data in CSV, Excel, PDF, or copy format. Here is the HTML code snip ...

Incorporating a JavaScript workflow into Django

Currently, I am following a tutorial on integrating a modern JavaScript pipeline into my Django application. The objective is to have the JavaScript code write "Hello webpack" onto the page, but unfortunately, it is not displaying as expected. Since I alr ...

Sorting table tbody elements created dynamically with JavaScript on an npm webpack application is not possible with jQuery UI

My JS-built table is populated with data from a JSON file fetched after a request. I want to be able to drag and drop these tbodys and update the JSON file accordingly. To handle sorting, I decided to use jquery-ui. While .sortable() works well for drag a ...

Defined a data type using Typescript, however, the underlying Javascript code is operating with an incorrect data type

Recently delving into Typescript and following along with an educational video. Encountered a strange behavior that seems like a bug. For instance: const json = '{"x": 10, "y":10}'; const coordinates: { x: number; y: number } = JSON.parse(json); ...

The destination where data is transmitted via POST to a PHP file using the HTTPRequestObject.send method

Can anyone help me figure out where the HTTPRequestObject stores strings that I have sent using the "POST" method to a PHP file? I have checked both the $_POST and $_REQUEST arrays but cannot find them. This is how I am sending the data from JavaScript: ...

Node server encountering issue with undefined data in POST request

I have been working on an Angular2/Node.js application. Everything seems to be working fine when I retrieve an object from the Node server, but I'm facing an issue when trying to post data to the server. The request.body always shows as undefined. Can ...

What is the process for transforming a method into a computed property?

Good day, I created a calendar and now I am attempting to showcase events from a JSON file. I understand that in order to display a list with certain conditions, I need to utilize a computed property. However, I am facing difficulties passing parameters to ...

What is the best method to trigger a reevaluation of static parameters?

Explanation behind my question Every day, I am sent two timestamps through MQTT at 01:15 - these timestamps represent the beginning and end of a daily event (in this case, when my children are at school). It may not be the most exciting information for a ...

Updating data-bind ng-model textarea in AngularJS scope is not reflecting changes

I encountered an issue while trying to reset a textarea using a function that I created. The problem is that although the scope updates as expected, the textarea bound by ng-model does not update. Below is a simplified version of the code: In Controller ...

Error in Node.js: Unable to access properties of null value within Express

While using Express (with node.js) and MongoDB, I encountered an error when trying to view or update a user profile. The middleware token check worked fine getProfileFields:::::::::::::>>>>e: TypeError: Cannot read properties of null (rea ...

Combining user input with React's useState function

I have a form with three Quantity inputs. (Although more can be added dynamically, let's keep it simple for now and stick to three.) | - | - | Quantity | |---|---|----------| | - | - | 3 | | - | - | 4 | | - | - | 5 | Now, I want ...

Autofill functions may not be compatible with input fields generated using JavaScript

Having trouble with browsers not using autocomplete in login overlays generated with JavaScript? It can be really annoying. Any suggestions on how to fix this issue? Should I create a hidden form within the original HTML and then move it into the overlay? ...

The alteration of arrays within React.js

I've been working on this function: setNotActiveWalletsList = () => { const { GetAccounts } = this.props; let shallowCopyOfWalletsArray = [...GetAccounts]; const notActive = shallowCopyOfWalletsArray.filter(user => user.active != ...

Managing authentication tokens in next.js

I'm currently working on a next.js app that requires authorization for certain functionalities. In the past with CRA, I would store the token in a config.js file and easily import, use, and update it throughout my application. Here is an example of ho ...