Issue with AngularJS: Controller unable to access property of ng-model object

I am looking to create a reusable controller that can be used by multiple views. This controller will essentially serve as a template.

The issue I'm facing is with setting up simple validation. The problem lies in the fact that the properties set in ng-model cannot be read unless changes are made to a field, which then adds that property to the object.

I am reluctant to include

ng-init="object.fieldName = null"
on every field in my view as I do not consider it to be good practice. While attempting to use $watch, I found that the object remained empty {}.

Below is the Controller code snippet:

angular.module('practiceApp')
.controller("CreateModalController", function($scope, items, defaultService) {

    function initialize() {
        $scope.object = {}; // <---- this should contain the ng-model object properties
        $scope.defaultService = defaultService;
        $scope.modalTitle = items.modalTitle;

        $scope.$watch('object', function(newValue, oldValue) {
            console.log(newValue);
        }, true);
    }

    initialize();

});

Here's what my view looks like:

<form name = "objectForm"
      role = "form">
      <input type="text" 
             ng-model="object.firstName" 
             class="form-control"
             placeholder="First Name" 
             ng-class="{'error-textfield': defaultService.isNotValid(object.firstName)}"
             required>

      <input type="text" 
             ng-model="object.lastName" 
             class="form-control"
             placeholder="Last Name" 
             ng-class="{'error-textfield': defaultService.isNotValid(object.lastName)}"
             required>
</form>

Current output => object: {}

Desired output =>

object: {firstname: undefined, lastName: undefined}

Answer №1

At first, the output will be object: {} because you haven't given any properties to $scope.object. Only the firstName or lastName property becomes visible when you input text into the <input> triggering ng-model to update $scope.object.

If you want the desired output initially, define your object in the controller with undefined properties:

$scope.object = {
  firstName: undefined,
  lastName: undefined
};

By the way, there's no need for self-initialization using initialize() function if the controller is already declared in your routing.

Furthermore, for AngularJS 1.5+ components, consider using $onInit().

Answer №2

Check out the following code snippet:

<!DOCTYPE html>
<html>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>

<script>
  
  
  var app = angular.module('practiceApp', []);
  app.controller("CreateModalController", function($scope) {

    function initialize() {
        $scope.object = {
          firstName: null,
          lastName: null
        }; // <---- the ng-model object properties should be placed here
        //$scope.defaultService = defaultService;
        //$scope.modalTitle = items.modalTitle;

        $scope.$watch('object', function(newValue, oldValue) {
            console.log(newValue);
        }, true);
    }

    initialize();

});
  
  
</script>
<div ng-app="practiceApp" ng-controller="CreateModalController">
<form name="objectForm"
      role="form">
      <input type="text" 
             ng-model="object.firstName" 
             class="form-control"
             placeholder="First Name" 
             ng-class="{'error-textfield': defaultService.isNotValid(object.firstName)}"
             required>

      <input type="text" 
             ng-model="object.lastName" 
             class="form-control"
             placeholder="Last Name" 
             ng-class="{'error-textfield': defaultService.isNotValid(object.lastName)}"
             required>
  
</form>
  </div>
</body>
</html>

Even if you choose not to initialize values, you will still see the values of firstName and lastName after typing in the input fields. When a user does not enter anything into the input fields, there are no values in 'object' to display.

Do you have any questions?

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

Choose all elements with a specific class name without the need to specify their position in the list

I'm working on adding a function to my WordPress site that will allow me to show/hide page elements with a specific class. For example, I want any elements (such as rows, containers, and text blocks) that have the 'show-hide' class to be hid ...

Having difficulty accessing the sound file despite inputting the correct path. Attempts to open it using ./ , ../ , and ../../ were unsuccessful

While attempting to create a blackjack game, I encountered an issue. When I click the hit button, a king card picture should appear along with a sound. However, the sound does not play and the error message Failed to load resource: net::ERR_FILE_NOT_FOUND ...

Tips for refreshing a specific div element at set intervals using JQuery AJAX?

I need to make updates to a specific div element without refreshing the entire HTML page. The code below currently works, but it reloads the entire HTML page. Additionally, I am working with different layouts where I have separate files for the header, l ...

unable to view the outcome of an ajax request

I am encountering an issue where I am trying to save an AJAX response to the Post PHP variable and display it on the same page. However, I keep getting a "Notice: Undefined index" error. I believe the problem lies in the success part of the AJAX call. Can ...

Troubleshooting NPM installation failures with SQLite build

After updating to macOS Mojave and installing the latest versions of node 12.1.0, npm 6.9.0, brew 2.1.1, and Python 2.7.10 on darwin, I encountered an issue while running npm install in a package.json file for a project that includes "sqlite3": "4.0.6". ...

Swap out .h and .m files within an iOS project's bundle directory in real-time

I am currently using the calculation.h and calculation.m files for some calculations in my project. These calculations may need to be modified while the application is live on the store. Therefore, I can only make changes to these calculations and update t ...

AngularJS object attribute - attribute preceded by "@"

After converting an XML document to JSON using C# and the Newtonsoft library, I encountered an issue where XML element attributes were prefixed with an "@". This JSON data is fetched from an $http service in AngularJS, then converted into an Angular objec ...

Can someone help clear up this confusion with CSS?

Why is image 6.png selected, when all the images are direct descendants of the div shape? Thank you for your assistance, it's greatly appreciated. As far as I know, it should select all the divs because they are all direct descendants of the div #shap ...

Retrieve main page elements from an additional page called PageSlide

I have implemented the jquery PageSlide plugin as a menu feature on my website. The plugin opens a separate page on the side of the main page to function as a menu. However, I am facing a challenge in accessing the main page's elements from this side ...

Achieving proper functionality of additional directives within uib-tab components

How can I utilize a callback function for uib-tab directives to refresh inner directives after tab rendering? I'm troubleshooting an issue with a third-party directive when used within the uib-tab directive from angular-bootstrap. The specific direct ...

What is the best way to retrieve the state value in react once it has been changed?

How can I ensure that the react state 'country' is immediately accessible after setting it in the code below? Currently, I am only able to access the previous state value in the 'country' variable. Is there a method such as a callback o ...

Three.js - Optimizing and Handling Images - Best Practices

My current project has a unique concept: https://i.sstatic.net/Jd3Ot.jpg The main idea revolves around a virtual room that dynamically adjusts its height based on the number of images loaded by the user. While it functions smoothly with fewer pictures, ...

Error: Authentication error. fatal: Unable to access the remote repository." encountered while executing the command "yarn install

Today, while developing a web application, I encountered an issue with the "yarn install" command. Upon running "yarn install", the console displayed an error message: "Host key verification failed. fatal: Could not read from remote repository." I attemp ...

Finding unique data stored in separate JSON files and loading them individually may require using different methods for

I have two JSON files named marker.json and marker.json0 that contain different latitude and longitude coordinates. To load them, I need to rename .json0 to .json (and vice versa), so that the new data from marker.json0 now resides in marker.json. This way ...

Mongoose: When encountering a duplicate key error (E11000), consider altering the type of return message for better error handling

When trying to insert a duplicate key in the collection, an error message similar to E11000 duplicate key error collection ... is returned. If one of the attributes is set as unique: true, it is possible to customize this error message like so: {error: ...

Accessing Angular templates scope after the document is ready using angular.element()

I am currently learning Angular and experimenting with the Symfony2 + AngularJS combination. I am facing a specific issue that I need help with: Within my index.html file, I have the following script: <script> global = {}; $(document).ready ...

Encountered an error while trying to access an undefined property during an Angular Karma

I'm currently working on testing a service function that involves multiple $http.get() calls. The function being tested returns a promise but the test is failing with an error stating response is undefined. Below is the test script: it('should ...

Significant lag experienced when using $rootscope.$on with a large object

In my AngularJS project, I am working with a JavaScript object (factory) that contains numerous functions spanning 4000 lines. Creating the object from data fetched from PHP happens pretty quickly. $http.get('pivots/list.php') .succe ...

Show only half of the Google Charts

I have a code snippet that displays a chart with dimensions of 500x500. However, I only want to show half of the chart, like 500x250. But whenever I adjust the values in the div, it resizes the entire chart instead of just showing half. My goal is to hide ...

Looking to pass the `Item Index` to functions within v-list-item-action in Vuetify?

Is there a way to pass the item index as a parameter to the function within the v-list-item-action element? Thank you in advance! <v-list-item v-for="(layer, i) in layers" :key="i"> <template v-slot="{ item, index }& ...