Remove the model from operation

I'm fairly new to angularjs and have a working service. However, I want to move the patient model out of the service and into a separate javascript file. I believe I need to use a factory or service for this task, but I'm not entirely sure how to go about it.

This is my patient.service.js:

(function () {
'use strict';

angular
    .module('beincharge.patient')
    .factory('patientDataService', patientDataService);

patientDataService.$inject = ['$http'];

function patientDataService($http) {
    var service = {
        getData: getData
    };

    return service;

    //////////

    function getData() {
       function patient(d) {
            this.Status = d.Status;
            this.ImageUrl = d.ImageUrl;
            this.PersonId = d.PersonId;
            this.LastName = d.LastName;
            this.MiddleName = d.MiddleName;
            this.FirstName = d.FirstName;
       }

        var data = [
            {
                "Status": "Active",
                "ImageUrl": "http://lorempixel.com/100/100/people/9/",
                "PersonId": 1,
                "LastName": "Pratt",
                "MiddleName": "B",
                "FirstName": "Allie"
            },
            {
                "Status": 'Active',
                "ImageUrl": "http://lorempixel.com/100/100/people/3/",
                "PersonId": 1,
                "LastName": "Pratt",
                "MiddleName": "B",
                "FirstName": "Allie"

            }];

             return  getPatientList(data);

             function getPatientList(data) {
                 var a = [];
                 angular.forEach(data, function (d, i) {
                     a.push(new patient(d));
                 })
                 return a;
             }



    }
}

I want to move the model into a file called patient.model.js:

  (function () {
    function patient(d) {
        this.Status = d.Status;
        this.ImageUrl = d.ImageUrl;
        this.PersonId = d.PersonId;
        this.LastName = d.LastName;
        this.MiddleName = d.MiddleName;
        this.FirstName = d.FirstNa
    }
    return patient;
}());

Answer №1

To implement a factory provider, you need to follow this structure:

angular
    .module('beincharge.patient')
    .factory('Patient', function() {
         return function(data){
             this.Status = data.Status;
             this.ImageUrl = data.ImageUrl;
             this.PersonId = data.PersonId;
             this.LastName = data.LastName;
             this.MiddleName = data.MiddleName;
             this.FirstName = data.FirstName
         }
     });

Then in the Service, you can utilize it as follows:

angular
    .module('beincharge.patient')
    .factory('patientDataService', patientDataService);

patientDataService.$inject = ['$http', 'Patient'];

function patientDataService($http, Patient){
    console.log(new Patient({ Status: 'active' }));
}

For a complete example, you can refer to the link below:

https://jsfiddle.net/9af3qys7/1/

Answer №2

If you are looking for a model that you can easily instantiate and reuse, consider creating a basic JavaScript object like the one shown below in a file named patientModel.js:

 function PatientModel() {
        this.Status = "";
        this.ImageUrl = "";
        this.PersonId = "";
        this.LastName = "";
        this.MiddleName = "";
        this.FirstName = "";
    }

Ensure that this file is loaded prior to the controllers or services where you intend to utilize it.

To create an instance of the model, you can do the following:

var patient = new PatientModel();

If needed, you can modify the constructor function to accept parameters so that you can pass any required data through the 'd' parameter.

This approach is suitable for simple and reusable models. The benefit is that you can also use them in your tests without having to depend on hardcoded JSON objects.

Answer №3

It seems like you're attempting to write JavaScript code with a Java style approach. In this case, creating a patient model may not be necessary as the response/data aligns directly with the patient object. A simpler implementation could be as follows:

(function () {
'use strict';

angular
    .module('beincharge.patient')
    .factory('patientDataService', patientDataService);

patientDataService.$inject = ['$http'];

function patientDataService($http) {
    var service = {
        getData: getData
    };
    return service;

    this.getData = function () {
        var data = [
        {
            "Status": "Active",
            "ImageUrl": "http://lorempixel.com/100/100/people/9/",
            "PersonId": 1,
            "LastName": "Pratt",
            "MiddleName": "B",
            "FirstName": "Allie"
        },
        {
            "Status": 'Active',
            "ImageUrl": "http://lorempixel.com/100/100/people/3/",
            "PersonId": 1,
            "LastName": "Pratt",
            "MiddleName": "B",
            "FirstName": "Allie"

        }];
        return data;
    };
}

Answer №4

It is recommended to transfer the app.service(..) code into the patient.model.js file for better organization.

 var app = angular.module('beincharge_patient',[]);

 app.service('patientData',function(){
   var getP = function(d) {
      this.Status = d.Status;
      this.ImageUrl = d.ImageUrl;
      this.PersonId = d.PersonId;
      this.LastName = d.LastName;
      this.MiddleName = d.MiddleName;
      this.FirstName = d.FirstName;
    }
    var service = {
      getP: getP
    }
    return service; 
 });

app.factory('patientDataService',['$http','patientData',function($http,patientData){
  
    var getData = function() {
      var data = [{
          "Status": "Active",
          "ImageUrl": "http://lorempixel.com/100/100/people/9/",
          "PersonId": 1,
          "LastName": "Pratt",
          "MiddleName": "B",
          "FirstName": "Allie"
        },
        {
          "Status": 'Active',
          "ImageUrl": "http://lorempixel.com/100/100/people/3/",
          "PersonId": 1,
          "LastName": "Pratt",
          "MiddleName": "B",
          "FirstName": "Allie"
        }
      ];      
       var getPatientList = function(data) {
        var a = [];
        angular.forEach(data, function (d, i) {
            a.push(new patientData.getP(d));
        })
        return a;
      }
       return  getPatientList(data);
    }
    var service = {
      getData: getData
    };
    return service;
}]);

 app.controller('beincharge_patient_Controller',    ['$scope','patientDataService',function($scope,patientDataService){   
   $scope.temp=patientDataService.getData();
 }]);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.11/angular.min.js"></script>

<div ng-app="beincharge_patient" ng-controller="beincharge_patient_Controller">
  <br/>
  {{temp}}
</div>

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

Angular: Handling window resizing events in your application

To handle window resize events in a non-angular application, we typically use the following code: window.onresize = function(event) { console.log('changed'); }; However, in angular applications, it's not recommended to directly acc ...

Tips for validating a text input field depending on the selected value in a dropdown menu using AngularJS

When a user selects from the dropdown menu, they can choose between Number and Decimalnumber. If the user selects Number, the text box should only allow whole numbers (e.g. 22, 33, 444, 345436). The user should not be able to enter decimal values like 22 ...

PHP not displaying line breaks from JavaScript textarea

I am facing an issue while trying to generate a .txt file on my server upon form submission. Despite including newlines in the comment section, they do not show up in the resulting .txt file. Below is the code snippet I am using: Javascript function sen ...

Angular Oops! We ran into a small hiccup: [$injector:modulerr]

I am facing an issue with an angular js error angular.js:36 Uncaught Error: [$injector:modulerr] http://errors.angularjs.org/1.2.19/$injector/modulerr?p0=app&p1=Error%3A%20…gleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.2.19%2Fangular.min.js%3A18%3A139) ...

How can I resolve the issue of the input field added dynamically by JavaScript not appearing in the PHP $_POST variable?

I have a form nested within an HTML table. Using jQuery, I am dynamically adding input fields to the form. However, when I submit the form and check the $_POST array with var_dump(), the added fields are not showing up. Why is this happening? Below is th ...

Accessing Protected API Endpoint Fails Following Successful Login in Node.js Express API

After developing registration and login APIs with Express, Mongoose, and Node.js, I am currently testing them using Postman. The registration and login functionalities are functioning properly, as the tokens are successfully stored in both cookies and head ...

What is the best way to create random integers using JavaScript?

Is there a way to create a function called drawSomething(x, y, color, boolean) that will generate random integers for the position of x and y on the canvas, randomly select a color from red, yellow, or blue, and randomly assign true or false to the boole ...

How come useEffect runs only once even when multiple states in the dependency array of useEffect change simultaneously?

<div onClick={() => { updateValue1((x: number) => x + 1); updateValue2((x: number) => x + 3); }} > one? two? </div> const [value1, updateValue1] = useState(1); const [value2, updateValue2] = useState(1 ...

Is it possible to manipulate an Angular #variableName in order to retrieve an ElementRef for an HTML element?

Suppose I have a scenario where I create a button like this: <button #myButton>My Button</button> ...and then use ViewChild in the following way: @ViewChild('myButton', { static: true }) createButton: ElementRef; In this case, creat ...

Tips for selecting the correct row in a table while making edits using Angular

I'm currently working on an editable table feature, but I'm facing an issue where all rows turn into input fields once I start editing. How can I select only the row that I want to edit by clicking on it? Below is a snippet of my table structure ...

Make sure to close any existing Featherlight windows before trying to open another one

I'm setting up multiple featherlight instances when the page loads jQuery('.feedback').featherlight(jQuery( "#feedback-box" ), { closeIcon: 'close'}); jQuery('#imprint').featherlight(jQuery( "#imprint-box" ), { closeIcon ...

Streamline the testing process to ensure compatibility with jQuery version 2.x

I currently have a substantial JavaScript code base that is all built on jQuery 1.8. I am planning to upgrade to jQuery 2.1 in the near future and I am fully aware that many parts of my code will likely break during this process. Is there any efficient me ...

Is there a way to verify the presence of multiple array indices in React with TypeScript?

const checkInstruction = (index) => { if(inputData.info[index].instruction){ return ( <Text ref={instructionContainerRef} dangerouslySetInnerHTML={{ __html: replaceTextLinks(inputData.info[index].instruction) ...

`Shifting a spherical object from point A to point B along its axis`

I am currently working on a project that involves rotating a sphere from point A to point B on itself. After finding Unity3d code for this, I came across the following solution: Quaternion rot = Quaternion.FromToRotation (pointA, pointB); sphere.transform ...

I am looking to insert a jQuery value or variable into the plugin options

How can I insert a jQuery value or variable into plugin options? This is my current script: $(document).ready(function() { // var bannerheight = 580; if ($(window).width() < 2100) { var bannerheight = 410; var opts = JSON.parse( ...

Utilizing Spiderable within Meteor results in the replication of head content before it is presented in the body tags

Having trouble with my meteor site, thought it was Google indexing, now suspecting an issue with the Spiderable package. Meteor version 1.1.0.3 is in use, along with spiderable package and gadicohen:phantomjs as suggested by meteorpedia. The current issu ...

What is the process for incorporating a custom attribute into an element with Vue directives?

One of the challenges I'm facing is dealing with a custom attribute called my-custom-attribute. This attribute contains the ID for the element that needs to have the attribute added or removed based on a boolean value. Although I've implemented ...

"Upon populating an object with Mongoose, the return value is an

Recently, I set up a mongo database and created a Post model that has a reference to the User by _id. I wanted to retrieve information about the posts a user has made, so I implemented a callback function within exec() while populating the selected User. H ...

Dart Manual Injection Guide

What is the recommended method for manually injecting an instance in Angular Dart? Can you demonstrate with an example similar to the one below in AngularJS: var myInjector = angular.injector(["ng"]); var $http = myInjector.get("$http"); ...

Reloading issue with NextJs when utilizing next-i18next for translations on a specific

Having trouble with next-i18next in my app. Implemented everything correctly, but the layout keeps rerendering on pages with getStaticProps. Need to find a way to prevent this. Created a file named withStaticTranslations.ts for pages, but when trying to l ...