Error: I can't seem to find the 'addTopic' property in the undefined object. Is it missing?

After spending several days analyzing this issue, I have come to the realization that my understanding of AngularJS is still new. Therefore, I am seeking assistance from the community here. The problem I am facing pertains to saving a new topic on a forum that I am currently developing: My controller

module.controller('newTopicController', ['$scope', '$http', 'dataService', function ($scope, $http, $window, dataService) {
$scope.newTopic = {};

$scope.save = function () {

    dataService.addTopic($scope.newTopic)
    .then(function () {
        $window.location = "/#";
    },
    function () {
        alert("couldnt save topic");
    });
};
}]);

And my factory:

module.factory("dataService", function ($http, $q) {

var _topics = [];
var _isInit = false;

var _isReady = function () {
    return _isInit;
};

var _getTopics = function () {

    var deferred = $q.defer();

    $http.get("/api/topics?withReplies=true")
    .then(function (result) {
        angular.copy(result.data, _topics);
        _isInit = true;
        deferred.resolve();
    },
    function () {
        deferred.reject();
    });

    return deferred.promise;
};

var _addTopic = function (newTopic) {
    var deferred = $q.defer();

    $http.post("/api/topics", newTopic)
   .then(function (result) {
       var createdTopic = result.data;
       _topics.splice(0, 0, createdTopic);
       deferred.resolve(createdTopic);
   },
   function () {
       deferred.reject();
   });

    return deferred.promise;
};

return {
    topics: _topics,
    getTopics: _getTopics,
    addTopic: _addTopic,
    isReady: _isReady
};
});

Upon attempting to add a topic to the forum, I encountered an error message stating "TypeError: Cannot read property 'addTopic' of undefined" in the controller, specifically where dataService.addTopic($scope.newTopic) is called.

I'm also utilizing another controller that interacts with the same factory, but it shouldn't be causing any issues, correct?

Thank you for your assistance.

Answer №1

It appears there is an error in the following code snippet:

module.controller('newTopicController', ['$scope', '$http', 'dataService', function ($scope, $http, $window, dataService) {...}

To correct it, modify the code to this:

module.controller('newTopicController', ['$scope', '$http', '$window', 'dataService', function ($scope, $http, $window, dataService) {...}

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

Every time I enter npm start in the terminal, I consistently encounter this error

After developing a simple web app and posting it on my repository, I started encountering these persistent errors. npm ERR! code ELIFECYCLE – David 1 hour ago npm ERR! syscall spawn C:\Windows\system32\cmd.exe;C:\Users'usernam ...

What is preventing me from reading the input value in AngularJS using jQuery?

Just starting out with angularjs and I need help with this code sample: <ng-input theme='fumi' id='txtEmail' label='Email Address' icon='icon icon--fumi mdi mdi-select-all' style="font-size:medium;width:40%;"&g ...

NodeJs: the beauty of modularity

In my node.js application, I have the following file structure: app models user book controllers user book views user book I am looking to implement modularity in my app. How can I communicate with the book controller from the user controller? Wh ...

AngularJS and the select2 plugin from Angular-UI: User-selected option doesn't match the displayed selection

When a user chooses an option, a different selection appears as the chosen one. This issue is only present when select2 is enabled. Despite this, ng-model behaves as expected, causing the selected option to differ from what ng-model indicates. Interesting ...

In order to set a condition for the mat date picker to display a text box in Angular if the selected date is for someone under 18 years old

I need assistance with displaying a text field based on age validation. The requirement is to show the input field only if the age is less than 18. Below is the code snippet I am currently working with: <form [formGroup]="form"> ...

Trouble displaying images in relative paths on Cordova for Android

Images can be found here: C:\Users\username\Source\Repos\mobile-app\resources\icons\android config.xml <platform name="android"> <icon src="resources/icons/android/icon-36-ldpi.png" density="ldpi" / ...

Are there any tools available that can convert ThreeJS code into WebGL?

Are there any existing tools that can convert ThreeJS to WebGL? Or, could you provide guidance on creating a converter for ThreeJS to WebGL? ...

The functionality of $viewContentLoading appears to be malfunctioning

Before the content is loaded, I'm attempting to log a value. I am using $viewContentLoading within the init function, but the value is not being logged. Can anyone help me identify the issue with my code? var app = angular.module('plunker&apos ...

What steps should I take to implement user access control in my current AngularJS application?

I have developed a login authentication application using AngularJS, but now I want to transform it into a user access control app. Can anyone provide suggestions on how to achieve this? Any help in guiding me through the process of enhancing my app would ...

Error in JSON: Unexpected character "<" found at position 8

Hi there, I encountered an error while trying to execute the ajax function. SyntaxError: Unexpected token < in JSON at position 8 at JSON.parse (<anonymous>) at parseJSON (jquery?v=M6dmVkrHVhoZ1gfOtvVDZbgBcQTsbWxoLsRizcGkbPk1:1) at vo ...

Creating a Timeless Banner with the Magic of `background:url()`

I have a banner placed within a div tag that displays my banner image. I am trying to create a fading effect when transitioning to the next image, but I am struggling to achieve this. I attempted to use jQuery fadeIn(), however, it did not work as expected ...

Experiencing a dependency injection issue when attempting to include ngRoute into the dependencies

In my AngularJS app, I have included the ngRoute dependency for routing and created a service for making REST calls. However, when I try to inject the dependency with ngRoute, I encounter the following error: angular.min.js:6 Uncaught Error: [$injector:mo ...

Using Django to retrieve data from a file uploaded through a website

Looking to create a website that allows users to select a local file (XML/JSON) and then navigate to a Django view to extract data from it. Should I implement javascript for the file selection form and sending it to a specific URL for the Django view? Any ...

Encountering "Error: Class constructor vA cannot be invoked without 'new'" when using Angular 10 Kendo Grid

I am currently working on integrating a Kendo Grid into my Angular application. However, I have run into an error when enabling the Kendo Grid component: vendor.4add67dadae0cd9152b9.js:16 ERROR Error: Uncaught (in promise): TypeError: Class constructor vA ...

Dealing with the element not present error in Protractor can be managed by using various

Is there a way to achieve similar Exception handling in Protractor as we can with Selenium webdriver in Java? When dealing with element not found exceptions, what is the most effective approach to handle them using Protractor? ...

Having difficulty in sending SMS through smsgateway.me following the recent update

Today, I encountered an issue while trying to send SMS messages programmatically using PHP from localhost. The problem arose after updating to version 4 of smsgateway.me and I am unable to send any messages. I am struggling to figure out how to pass the AP ...

Obtain Outcome from a Nested Function in Node.js

I'm grappling with the concept of manipulating the stack in JS and hoping this exercise will provide some clarity. Currently, I'm attempting to create a function that makes a SOAP XML call, parses the data, and returns it when called. While I c ...

Display the Vaxis line in a bar graph using Google Chart

Currently, I am involved in a project where I need to display a graph that resembles the one depicted here. To accomplish this task, I am utilizing the Google Visualization Chart API. Successfully, I have managed to generate the chart as illustrated below ...

What is the best way to invoke a method within a method in Angular 1.x?

Here is a breakdown of my HTML structure: Controller Side: <div ng-controller="Ctrl"> <first-directive></first-directive> </div> First Directive HTML: <li> <second-directive></second-directive> </li> C ...

Interactive web page with dynamic JQuery functionality and navigable page links

I am working on the project/index.html page <html> <head> <title>Index</title> <scripts...> </head> <body> Hello <div id="content"></div> <button id="page1" value="page1"/> <but ...