Resetting the value of an object property

My query concerns a provider:

AdviceList.provider('$adviceList',function(){
    this.$get = function ($rootScope,$document,$compile,$http,$purr){

        function AdviceList(){

          $http.post('../sys/core/fetchTreatments.php').success(function(data,status){
                this.treatments = data;
                console.log(this.treatments); // the correct object
            });

            this.adviceCategories = [
                // available in the controller
            ];

        }
        return{

            AdviceList: function(){
                return new AdviceList();
            }
        }
    }
});

In addition, I am utilizing this controller:

AdviceList.controller('AdviceListCtrl',function($scope,$adviceList){
    var adv = $adviceList.AdviceList();
    $scope.treatments = adv.treatments; // undefined
});

I am puzzled as to why the controller's $scope.treatments remains undefined, although this.treatments within the provider is properly populated. Moreover, adviceCategories is accessible in my controller.

Answer №1

When you receive treatment, it is important to note that the process is asynchronous, which means the results may not be available immediately.

Therefore,

var adv = $adviceList.AdviceList();
$scope.treatments = adv.treatments;  //The treatments will be populated after the server call is completed.

To ensure that the code is executed correctly, make sure to assign it to your scope property within the success callback function.

Answer №2

I suggest simplifying your code by following these steps:

1) Instead of using provider, switch to Angular's simple factory method.

2) Opt for returning a promise over using callbacks.


AdviceList.service('adviceList', function ($http) {
    return {
        adviceList: function () {
            return $http.post('../sys/core/fetchTreatments.php');
        }
    }
});

AdviceList.controller('AdviceListCtrl', function ($scope, $adviceList) {
    adviceList.AdviceList().then(function (data) {
        $scope.treatments = data; // Set the value to data when received from the server
    });
});

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

Model is updated by checkbox only on the second click

Take a look at this Plunkr example here: http://plnkr.co/edit/hwVL3xtnD9hGJL?p=preview After clicking the checkbox for the first time, the model fails to update. Can you explain why? var app = angular.module('main', ['ngMaterial']) ...

Angular Material UI dropdown menu

Currently, I am in the process of incorporating a select dropdown using Angular Material UI. <md-select class="width-100" placeholder="Priority" data-ng-model="task.priority"> <md-option value="one">One</md-option> <md-option ...

Iframe displaying a blank white screen following the adjustment of document.location twice

I am in the process of developing a web application that I intend to integrate into my Wix website. The main components of the required web application are a text screen and a button to switch between different screens/pages (html content). However, I am ...

Submitting a form using jquery

I am working on a project that involves using a jquery fancyzoom box. Within this box, there is a contact form that should send an email upon submission. However, I am encountering issues with calling the form submit function due to the fancyzoom feature. ...

Script designed to track modifications on a specific webpage

Attempting to purchase items online has become a frustrating challenge as stock seems to disappear within minutes of being added :/ I am currently working on creating a custom grease/tampermonkey script to monitor the page and notify me when products beco ...

Issue: Module '../utils/composeObjs' not found after global installation of generator-stencil

Currently, I am in the process of developing a generator for stenciljs which can be found at https://github.com/AkashGutha/generator-stencil Within this project, there is a handy utility function located at the root directory. This function resides in one ...

Guide on integrating AngularJS routes with Express (Node.js) to handle requests for a new page

When using Express to load AngularJS from a static directory, my usual request is http://localhost/. Express serves me the index.html file along with all the necessary Angular files. In my Angular app, I have configured routes that replace content in an ng ...

Retrieving selected values from a dynamic Primeng checkbox component

Within my Angular app, I am managing an array of questions. Each question includes a text field and an array of string options to choose from. The questions are retrieved dynamically from a service and can be updated over time. To allow users to select mul ...

The latest version of Material UI, v4, does not currently support React 18

Looking to incorporate MUI (Material UI) into my website design. Encountering difficulties with installing this library, receiving the error message below: -npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve dependency tree npm ERR! npm ERR! While ...

What is the best method for dynamically adding a phone number to an href link?

Is there a way to dynamically insert a phone number into the href attribute for tel: <q-item tag="a" href="tel:1234567890" clickable v-ripple> ...

Changing the value of a nested object in React's state

In my web application, I am using React/Redux with a Description Class that allows users to edit descriptions. The Props description and propertyTypes are fetched through AJAX calls. import React, { PropTypes } from 'react'; const defaultDesc ...

Learn how to import MarkerClusterer from the React Google Maps library without using the require method

The sample provided utilizes const { MarkerClusterer } = require("react-google-maps/lib/components/addons/MarkerClusterer");, however, I would prefer to use the import method. I attempted using: import { MarkerClusterer } from 'react-google-maps/lib ...

Using inline SVG within a Vue.js component

Recently, I embarked on a Vuejs project using @vue/cli version 3.0.0-beta.16. In my Home.vue single file component, I encountered an issue while trying to import and add inline SVG to the template. The crux of the problem lies in the fact that vue cli alr ...

- Determine if a div element is already using the Tooltipster plugin

I have been using the Tooltipster plugin from . Is there a way to check if a HTML element already has Tooltipster initialized? I ask because sometimes I need to update the text of the tooltip. To do this, I have to destroy the Tooltipster, change the tit ...

Using PHP to read an image blob file from an SVG

Currently, I am utilizing the Raphael JS library on the client-side to generate a chart in SVG format. However, my goal is to make this chart downloadable, which poses a challenge since SVG does not natively support this feature. Initially, I attempted to ...

Ways to incorporate a pause between functions being executed

I'm working on a chatbox feature using socket.io and I'm interested in adding a delay between message sending to prevent spam. Can someone provide guidance on how to achieve this? Below is the code snippet for sending a message in my project: // ...

Jstree: Whenever I refresh my tree, the checkboxes do not reset to default and remain unchecked

After attempting to implement the following code: $("#jstree_demo_div").jstree("destroy").empty(); Although it successfully removes the checked nodes and reloads the tree, it fails to apply the new changes. Any advice on how to resolve this issue would b ...

Creating dynamic drop-down menus using PHP, HTML, JavaScript, and MySQL

I need help with a form where users are required to select departments and based on that, the corresponding defect fields should populate with matching defects. Currently, when I try removing Defect 4, Defect 3 works; remove 4 & 3, then 2 works and so fo ...

The renderToString function in Material UI's sx property doesn't seem to have

Every time I apply sx to a component that is rendered as a string and then displayed using dangerouslySetInnerHtml, the styles within the sx prop do not work. Here is an example showcasing the issue: Codesandbox: https://codesandbox.io/p/sandbox/wonderfu ...

When using nodejs, a valid command line prompt fails to execute or spawn due to an ENOENT error

One day, I came across a bash command (debian 10, GNU bash, version 5.0.3(1)-release (x86_64-pc-linux-gnu)): documents=("/data/sice.pdf" "/das00/12ser.pdf");bash ./clean-pdfs.sh "${documents[*]}" This command worked perfectly ...