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

Tips for connecting a Django API project with a nodejs and react frontend

I'm currently working on a Django API project and I am considering incorporating Node.js into the mix. Additionally, I am interested in using React for the frontend of the application. Is this combination of technologies feasible? Would it be advisabl ...

When employing ng-repeat, the ui-bootstrap tooltip fails to function as expected

I'm trying to implement tooltips for a series of buttons using the ui-bootstrap tooltip directive within an ng-repeat loop, as shown below: <button ng-repeat="label in labels" tooltip="{{label}}">{{label}}</button> However, I've enc ...

Implement and remove changes in mongodb

My database sample looks like this: db={ "sample": [ { current_book: "Aurthor", upcoming_book: [ "Sigma", "Rocky" ] } ] } I am trying to update the current_book value to ...

Ways to center the percentage on the progress bar

I'm having an issue with positioning the percentage 100% in the center of the element. I attempted adjusting the spacing in the JavaScript code, but so far it hasn't been successful. Here is the current output for the code: http://jsfiddle.net/G ...

The ng-checked attribute is not working as expected and being overlooked for the checkbox

I am facing an issue with a checkbox in my code. The checked state (ng-checked) of the checkbox is determined by a computed property (ng-checked="someFunction()"). Let's say the checkbox should always be checked, meaning the value should be ng-checke ...

Search for objects in the array that have the same name, and then combine the values of those matching

I've done some research on various platforms, but haven't come across a solution to my specific issue. I'm looking to extract objects from an array and group them by their names in order to calculate the total hours for each matching object. ...

Ways to retrieve information beyond the scope of the 'then' method

One issue I am facing involves a piece of code that is only accessible inside of the 'then' function. I need to access it outside of this block in order to utilize it in other parts of my program. $scope.model = {'first_name':'&ap ...

Effortless integration of jQuery with Google Maps autocomplete feature

I've successfully implemented Google Maps Autocomplete on multiple input tags like the one below: <input class="controls pac-input" id="pac-input" type="text" onfocus="geolocate()" placeholder="Type custom address" /> To enable Google Maps au ...

Is the z-index feature not functioning as anticipated?

I'm currently working on a project involving a book that flips on click on both sides. The process involves checking the direction when a page is clicked and flipping it to the left if it's not to the right. Additionally, I adjust the z-index to ...

Steps for regularly executing 'npm run build' on the server

My website doesn't require frequent content updates, as users don't always need the latest information. As a result, most pages are generated server-side and served as static pages. There will be occasional database updates that need to be visib ...

The issue with the trigger function in jQuery is specifically affecting Chrome browser

When attempting to load a modal window using a link like , I am encountering issues in Chrome, Safari, and IE. However, Opera and FF are functioning properly. The modal window is being called as an iframe. Other buttons that are supposed to open the modal ...

Transferring Python Data to JavaScript using Django

Currently, I am utilizing Django and Apache for webpage serving purposes. In my JavaScript code, I have a data object that contains values to be exhibited in HTML widgets based on the user's selection from a menu. I am looking for a way to derive this ...

Using regular JavaScript with code inside ng-view in AngularJS involves incorporating event listeners and manipulations that can interact

Just delving into the world of angularJS for the first time. I've set up the routing service, which involves having a div with routing that calls in a template containing HTML code. I also have a range of regular JavaScript functions necessary for the ...

What are some strategies for safeguarding a disabled button?

Is there a way to securely disable a button if the user does not have permission to access it? I currently disable it at the Page_Load event: Page_Load() { if(!userhasrights) { btn.Enabled=false; } } However, after rendering, ASP.N ...

Transitioning between javascript functions

Having some issues with a switch case statement, also tried using if-else but no luck. In the HTML code: <select onBlur="functionCalc()" id="art"> <option value="hours" id="hours">Hours</option> <option value="minutes" id="mins">M ...

Displaying a list of values in Angular using data retrieved from an Entity Framework query

Is there a way to populate a list (ul li) with data from an array that is populated through Entity Framework code? Currently, I am able to populate an option dropdown successfully using the following code: <select class="form-control" name="Search" ...

Struggling to make JavaScript read JSON data from an HTML file

I am currently working on developing a word search game using django. One of the tasks I need to accomplish is checking whether the entered word exists in a dictionary. To achieve this, I have been converting a python dictionary into JSON format with json. ...

Building a High-Performance Angular 2 Application: A Comprehensive Guide from Development to

Recently, I began developing an Angular2 project using the quickstart template. My main concern now is determining which files are essential for deployment on my live server. I am unsure about the specific requirements and unnecessary files within the qu ...

Link clicking does not trigger URL routing properly

I've been tasked with updating our web application, and I'm facing a challenge that I need help with. My boss wants users to be able to click on a link in an email and have the internal company web app directly navigate to a specific page indicat ...

Removing chips in Material UI can be easily accomplished by following these steps

Recently, I implemented a feature where chips are generated as the user types in a text field and clicks on create. A chip is then displayed with the entered text. Now, I am looking to add the ability to delete these chips dynamically. You can view the s ...