AngularJS: The art of object pushing

I have a small application where I need to read data from a JSON file, display it, and allow users to add records to it. Specifically, I have an array called condition within the patient object, and I want to insert a new item into this array based on user input. The added data does not need to be stored or submitted via POST request.

I am unsure whether I should retrieve information from the Patient object or from $scope. There is no data submission involved.

Is the implementation of function addCondition correct?

/* Data */
angular.module('prototypeApp')
 .factory('MedicalRecords', function($http) {
   return $http.get('scripts/data/patient_record.json');
});

/* Add more Information to Patients Conditions */
angular.module('prototypeApp')
 .controller('PatientExtConditionCtrl', function ($scope, MedicalRecords) {
        MedicalRecords.success(function(data) {
        $scope.patient = data;
          });
 });

/* Confirm Patients Conditions */
angular.module('prototypeApp')
 .controller('PatientConditionCtrl', function ($scope, MedicalRecords) {
        MedicalRecords.success(function(data) {
        $scope.patient = data;
          });
 });

/* FormController */
angular.module('prototypeApp')
 .controller('AddConditionCtrl', function () {
   this.condition = {};

   this.addCondition = function(patient){
     patient.patientCondition.push(this.condition);
   };
 });


/* in my template */

<form name="AddConditionForm" ng-controller="AddConditionCtrl" ng-submit="AddConditionCtrl.addCondition(patient)">
    <input type="text" class="form-control" ng-model="AddConditionCtrl.condition.hcc">
    <input type="text" class="form-control" id="input_description" ng-model="AddConditionCtrl.condition.description">
    <input type="text" class="form-control" ng-model="AddConditionCtrl.condition.last_report">
    <button type="submit" class="btn btn-primary">Add</button>
</form>

<table class="table table-striped">
    <tr>
        <th>Code</th>
        <th>Condition</th>
        <th>Last Reported</th>
        <th>Check</th>
    </tr>
    <tr ng-repeat="condition in patient.patientCondition">
        <td>{{ condition.hcc }} </td>
        <td>{{ condition.description }}</td>
        <td>{{ condition.last_report | date }}</td>
        <td> Check </td>
        </tr>       
</table>
<form action="/#/patient/conditions/ext">
    <button type="submit" class="btn btn-primary pull-right">Next</button>
</form>

Answer №1

You're so close to getting it right.

Your addCondition function is perfectly fine. The issue appears to be a mix-up between the classic Angular controller syntax and the newer 'controller as' syntax.

Classic Syntax

  • The controller function receives $scope as a parameter and adds properties to it
  • The controller is linked with the view using ng-controller="controllerName"
  • Properties of $scope are directly accessible in the view (without any prefix)

    .controller('controllerName', function ($scope) {
        $scope.item = 1
    })
    
    <div ng-controller="controllerName">{{item}}</div>
    

'Controller As' Syntax

  • The controller function does not require $scope; instead, it assigns properties to this
  • The controller is connected to the view using
    ng-controller="controllerName as somePrefix"
  • Properties of the controller's this can be accessed in the view using somePrefix.fieldName

    .controller('controllerName', function () {
        this.item = 1
    })
    
    <div ng-controller="controllerName as ctrl">{{ctrl.item}}</div>
    

In your code, you've used the classic syntax for the first two controllers, but then switched to 'controller as' without specifying the as prefix in ng-controller="AddConditionCtrl". Make sure to update your binding to match the chosen prefix. For instance,

ng-controller="AddConditionCtrl as addCondition"
requires
ng-model="addCondition.condition.hcc"
.

The Angular team recommends adopting the 'controller as' syntax for clearer bindings, as it clearly associates fields with their respective controllers.

UPDATE: Assuming that your form element is within an element controlled by either

ng-controller="PatientExtConditionCtrl"
or
ng-controller="PatientConditionCtrl"
, the patient variable should be accessible when ng-submit triggers addCondition(patient).

UPDATE: More information on both syntaxes can be found in the official documentation for the ngController directive.

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

Creating an array of multiple divs based on numerical input

I am working on a project to show multiple divs based on the user's input number. For example, if the user selects 3, then 3 divs should be displayed. While I have successfully implemented this functionality, I need to dynamically assign IDs to each ...

Can new content be incorporated into an existing JSON file using HTML input and the fs.writeFile function?

I recently started learning about node.js and decided to create a comment section that is rendered by the node.js server. I successfully passed the value from a json file into an ejs file, which rendered fine. Now, I have added an input field and submit b ...

What is the best way to merge setInterval with mouseenter events?

I have successfully implemented code that refreshes a div using ajax. However, I am looking to add functionality so that the div only refreshes every 30 seconds when the tab is active. It seems that setInterval currently refreshes the div regardless of tab ...

Combining various API requests within a Vue component, which includes a for loop

I'm delving into the world of API chaining, specifically trying to link two different API calls within a 'notes' Vue component. My knowledge of promises is basic at best, but I'm eager to enhance my skills in this area. The initial API ...

Vows.js: Utilizing data from parent topics in nested topics

Is there a way to access the return value of an outer topic from within a test in an inner topic? To clarify, consider this example: "build.css" : { topic : function(file) { fs.readFile(fixtures + "/public/build.css", "utf8", this.callback); }, ...

Utilizing Material UI's (MUI) date picker in conjunction with react-hook-form offers a

I'm currently developing a form with a date field utilizing MUI and react-hook-form for validation. I have experimented with two different methods of rendering the field, but when I try to submit the form, the expected value is not being returned: Me ...

How to use JQuery UI sortable to automatically scroll to the bottom of the page

Having trouble with a few sortable tables and here is how I initialized the sortable object: var options = { helper: customHelper, handle: ".moveTargetDeliverables", containment: "#fieldset_deliverables_summary", tolerance: 'pointer&a ...

Update the value of a JavaScript variable in an HTML template by targeting the element with a specific

Within my testFile.html HTML file, the following code is present: <div id="image-type-placeholder">marinaa</div> In my JavaScript file: const CourseImageUpload = BaseComponent.extend({ /** * @property {function} */ templat ...

Timepicker Bootstrapping

I've been searching for a time picker widget that works well with Bootstrap styling. The jdewit widget has a great style, but unfortunately it comes with a lot of bugs. I'm on a tight deadline for my project and don't have the time to deal w ...

Adding a characteristic to every item in an array of objects

Currently, I am utilizing Node.js along with Mongoose to interact with a MongoDB database and retrieve an array of objects from a specific collection. However, my aim is to add an additional property to each of these retrieved objects. Below, you can see t ...

Is there a way to configure multiple entry points in a package.json file?

I am looking to execute various commands using npm: "scripts": { "v1": "node v1.js", "v2": "node v2.js" } I would like to use npm start v1 or npm start v2 for this purpose, however, these commands do not seem to trigger the intended Node command. ...

Validation error occurred while attempting to send form data to the Contact Form 7 API through Next.js

Having trouble sending data to the Contact Form 7 API and encountering an error while submitting the form: {into: "#", status: "validation_failed", message: "One or more fields have an error. Please check and try again.", post ...

Maintaining an onExit function in the ui-router framework

I am trying to implement an animation on an element within a page when the user is transitioning out of a state. Here is my current code snippet: { ....., views: { ... }, onExit: function(){ someEle.classList.remove("someClass"); // ...

Drawbacks of adjusting design according to screen width via javascript detection

When creating a website, I want it to be compatible with the most common screen resolutions. Here is my proposed method for achieving this: -Develop CSS classes tailored to each screen resolution, specifying properties such as width and position. -Write ...

Using AngularJS, learn how to populate array objects within a JSON object

I'm trying to load array objects from a multi-select control, then populate a model object called "name" with its name and age values. After that, I want to load an array from a select element into the model object. However, the ng-model directive on ...

Angular - Dividing Values within Input Arrays

In the input field available to users, they can enter multiple inputs separated by commas. <div class="container"> Enter your values:<input type="text" multiple #inputCheck> <input type="submit"(cli ...

I'm having trouble with ngBindHtml and trustAsHtml not functioning properly with ngModel in AngularJS version 1.2

Figured this would be a breeze since it worked like a charm in Angular 1.0.8 using ngBindHtmlUnsafe. However, after researching the API docs and StackOverflow, it appears that I now need to employ $sce.trustAsHtml() with ngBindHtml, but I can't seem t ...

Best methods for deleting an element's attribute or style attribute

Imagine this snippet of CSS code: .notif-icon { display: inline-block; } In my HTML, I have the following element which starts off hidden by overriding the display property of the notif-icon class: <span id="error" class="notif-icon& ...

Receiving a reply from the axios function

Whenever I try to call the lookUpItem function from ItemSearch.vue, I always get an undefined response. Code snippet from ItemSearch.vue: <script setup lang="ts"> import { lookUpItem } from '../systemApi' async fu ...

Using React to Calculate the Total Value of Child Components within the Parent Component

In this scenario, the parent component has access to the values of the child components but struggles to calculate the sum correctly. Instead of displaying the accurate total, it shows 0. https://i.sstatic.net/1etAx.png The expected behavior is for the To ...