Error: Attempting to access a property 'notesObjectInService' that is undefined on the object

I'm currently facing an issue where my controller is unable to load an object from a service called notesFactory. The console.log(typeof notesFactory) statement returns 'undefined', causing notesObjectInService to trigger an exception.

Despite reviewing the code multiple times, I can't pinpoint the error. As a newcomer to javascript and AngularJS, I might be overlooking something crucial. My suspicion initially fell on the postPromise, but I still struggle to grasp the intricacies of promises.

If anyone has insights or solutions to this problem, your help would be greatly appreciated.

 function NotesProvider(){
    this.$get= angular.noop
}
angular.module('theNotesApp2',['ui.router'])
     .config(['$stateProvider',
              '$urlRouterProvider',
              function($stateProvider, $urlRouterProvider){
                  $stateProvider
                      .state('home', {
                          url: '',
                          //the templateUrl value is the id for the routing
                          templateUrl: '/home.html',
                          controller: 'mainCtrl',
                          resolve: {
                              postPromise: ['notesFactory', function(notesFactory){
                                  return notesFactory.getAll();
                              }]
                          }
                      })
                      .state('navbar',{
                          url: '/navbar',
                          templateUrl: '/navbar.html',
                          controller: 'mainCtrl'
                      })
                      .state('notes',{
                          url: '/notes/{id}',
                          templateUrl: '/notes.html',
                          controller: 'notesCtrl'
                      });
                  $urlRouterProvider.otherwise('home');
              }
     ])

     .factory('notesFactory', NotesProvider,'$http' [function($http, NotesProvider){

        var notas = {notesObjectInService: []};

        notas.getAll() = function() {
             return $http.get('/notes.json').success(function(data){
                 angular.copy(data, notas.notesObjectInService);
             })
        };
        notas.create() = function(note){
            return $http.post('/notes.json', note).success(function(data){
                notas.notesObjectInService.push(data);
            })
        };

        return notas;
     }])

    .controller('mainCtrl',['$scope', 'notesFactory', function($scope, notesFactory){
        console.log(typeof notesFactory);
        $scope.notes = notesFactory.notesObjectInService;

        $scope.addNote = function(){
             if ($scope.title === "" ) {
                 return;
             }
             notesFactory.create({
                 title: $scope.title,
                 body:$scope.body
             });
             $scope.title= '';
             $scope.body= '';
         };
     }])
    .controller('notesCtrl', ['$scope', 'notesFactory', '$stateParams', function(
         $scope, notesFactory, $stateParams){
         console.log('test');
         $scope.note =
             notesFactory.notesObjectInService[$stateParams.id]
     }])

Answer №1

There are a couple of issues that need to be addressed. Firstly, there seems to be confusion with the array notation in the factory definition and the order of injected services.

Additionally, the object method definition should not include () after the method name:

notas.getAll = function () { /* ... */ };

A correct factory definition would appear as follows:

.factory('notesFactory', ['$http', 'NotesProvider', function ($http, NotesProvider) {

    var notas = {
        notesObjectInService: []
    };

    notas.getAll = function () {
        return $http.get('/notes.json').success(function (data) {
            angular.copy(data, notas.notesObjectInService);
        })
    };
    notas.create = function (note) {
        return $http.post('/notes.json', note).success(function (data) {
            notas.notesObjectInService.push(data);
        })
    };

    return notas;
}]);

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

Identifying flex-wrap capabilities across different browsers

Currently, I am developing a project that involves implementing a responsive grid using the flex wrap property. However, since my project needs to support IE9 and older versions of Firefox (version 28 and below), I am in need of a way to determine their ...

Can you please provide a method for determining which characters are adjacent to each other

I am in the process of developing a markdown editor and I require a check to identify if adjacent characters are specific characters, removing them if they match or adding them otherwise. For example, if the selected text is surrounded by two asterisks li ...

What is the best way to arrange images in a 3 by 3 grid, beginning at position 0, using JavaScript to control navigation through button clicks?

When I click on button 1, it starts at image 1 because the counter is set to 0. Clicking on button 2 takes me to image 4 with a counter value of 3, while clicking on button 3 leads to image 7 with a counter value of 6. The process should also work in reve ...

Display a dropdown menu when hovering over with a delay

I recently created a basic navigation menu with dropdown functionality using CSS3 initially, but I decided to enhance it by incorporating jQuery to display the dropdown after a set timeframe. However, I am facing an issue where all dropdowns appear when ho ...

Troubleshooting ASP.NET Content Page Error: jQuery Object Expected

Currently working on designing a personal ASP.NET Web page, I have encountered an issue with making a sticky div using jQuery. Despite all my other jQuery functions functioning properly, the sticky div seems to be causing trouble. stickydiv.js $(document ...

Vue-bootstrap spinbutton form with customizable parameters

I am in need of a custom formatter function for the b-form-spinbutton component that depends on my data. I want to pass an extra argument to the :formatter-fn property in the code snippet below, but it is not working as expected. <b-form-spinbutton :for ...

Tips on displaying each element of an array in a unique format within a React component

I am working on creating a component that will display data in boxes. Each set of constant data should be placed within a div for organization. Currently, I have a Box component that is responsible for displaying the data. The Tutorial component receives ...

Error: Unable to access the 'sid' property because it is undefined

I've been facing an issue where sending an SMS through Twilio's API Explorer works fine, but fails under my node installation. Despite a complete uninstall and reinstall, the problem persists. Error 7 Oct 21:28:37 - [nodemon] starting `node scr ...

What is the process for completing a form with Protractor and TextAngular?

I'm currently attempting to submit a form that utilizes TextAngular for certain input fields. Despite my efforts, I haven't been successful in finding information on how to fill out these fields. The closest solution I found was this, but when I ...

Is there a way to make my modal appear only when the "New" option is clicked?

Is there a way to make my modal in VueJS open only when I click on the "New" option? <select v-model="input.des" @change="$refs.modalName.openModal()"> <option value="A">A</opt ...

Changes to the className of a React component will trigger a re-render of

When the className of the parent changes, React children will re-render. import React from 'react'; import { useSelector } from 'react-redux'; import items from './ItemsList.js'; import Item from './Item'; import &ap ...

JavaScript prototype error: caught TypeError - attempting to call undefined function

I am facing challenges while attempting to create a Factory in AngularJS. I have moved the code from the controller to the factory and made a few adjustments for it to function properly. Here is the error that I am encountering: "El objeto no acepta la p ...

Unable to update state from within a function in react

As I delve into the realm of coding, a simple graph catches my eye. It showcases various data sets including current, all, and filtered data. Initially, the first block of code runs smoothly. However, upon attempting to setState in order to make some modif ...

Having trouble installing sqlite3? Encounter an issue like this: "srcdatabase.cc(35): error C2248: 'Napi::Env::DefaultFini': cannot access private member declared in class 'Napi::Env'"?

Encountering issues while trying to install sqlite3 for a Strapi app I've attempted using yarn to install sqlite3 in various ways, but to no avail. Below is the error log: Error message: Issue with installing sqlite3 when creating a Strapi app (..& ...

How to customize the text color of the notchedOutline span in Material UI

I'm currently working on customizing the textfield in materialUI. This is what I am trying to modify. I am facing challenges in changing the color of the span tag that contains the text, and also in maintaining the border color when the textfield is ...

transferring data from JavaScript to PHP variables

Currently, I am working on a project that involves using ajax to access the database asynchronously. The value retrieved is stored in a JavaScript variable like this: var content=xmlhttp.responseText; My next step is to pass this value to the PHP module ...

Disable the draggable feature upon clicking the button

I am currently working on a code challenge where I need to disable the draggable functionality of all divs styled with .myDivs when the user clicks the 'Remove Draggable' button. You can view my progress in this JSFiddle: http://jsfiddle.net/adri ...

Currently focused on developing vertical sliders that can be manipulated by dragging them up or down independently

https://i.stack.imgur.com/NgOKs.jpg# I am currently working on vertical sliders that require dragging up and down individually. However, when I pull on the first slider, all sliders move together. The resetAllSliders button should also work independently, ...

Unable to establish a connection with the docker container

I have developed a server-api application. When running the app on my localhost, only two simple commands are needed to get it up and running: npm install npm start With just these commands, the app runs perfectly on port 3000. Now, I am trying to dock ...

design facebook type box scroll bar

After extensively searching through various stackoverflow answers in an attempt to change the CSS for a Facebook likebox scrollbar, I have had no success. Below is the code that I am currently using: <div id="fb-root"></div> <script>(fun ...