Another function in AngularJS does not acknowledge the presence of a particular function

While loading the partial Html with controller, my function called $scope.actionViewVisitors() works perfectly without any errors. However, when I try to use it within another function in the same controller, an error occurs:

TypeError: $scope.actionViewVisitors is not a function
. Here's a snippet of my code:

angular.module("Visitor.controller", [])

// ============== Controllers
.controller("viewVisitorController", function ($scope, $rootScope, $http, viewVisitorService, viewAccountService, DTOptionsBuilder) {
    $scope.visitorList = null;

    $scope.viewAccountDetail = null;
    $scope.avatar = null;

    $scope.visitorDetail = null;

    $scope.visitorBtn = "Create";

    // Function to retrieve account details
    $scope.actionViewAccount = function () {
        $scope.actionViewAccount = viewAccountService.serviceViewAccount()
        .then(function (response) {
            $scope.viewAccountDetail = response.data.account;
            $scope.avatar = "../../avatars/" + response.data.account.AccountId + ".jpg";
        })
    }

    $scope.dtOptions = DTOptionsBuilder.newOptions()
        .withDisplayLength(10)
        .withOption('bLengthChange', false);

    // The following function throws an error    
    $scope.actionViewVisitors = function () {
        $scope.actionViewVisitors = viewVisitorService.serviceViewVisitors()
            .then(function (response) {
                debugger;
                $scope.visitorList = response.data.visitorList;
            });
    }

    // No error occurs here
    $scope.actionViewVisitors();
    $scope.actionViewAccount();

    $scope.createVisitor = function () {
        $scope.statusMessage = null;
        if ($scope.visitorBtn == "Create") {
            $scope.createVisitor = viewVisitorService.serviceCreateVisitor($scope.visitorDetail)
                .then(function (response) {
                    if (response.data.response == '1') {
                        bootbox.alert({
                            message: "Successfully created a new visitor.",
                            size: 'small',
                            classname: 'bb-alternate-modal'
                        });
                    } else if (response.data.response == '0') {
                        bootbox.alert({
                            message: "Failed in creating visitor.",
                            size: 'small',
                            classname: 'bb-alternate-modal'
                        });
                    }
                });
            debugger;
            $scope.visitorDetail = undefined;
            // Error occurs when calling this method
            $scope.actionViewVisitors();
        }
    }
})

// ============== Factories
.factory("viewVisitorService", ["$http", function ($http) {
    var fac = {};

    // Service to fetch visitor data
    fac.serviceViewVisitors = function () {
        return $http({
            url: '/Visitor/ViewVisitors',
            method: 'get'
        });
    }

    // Service to create a new visitor
    fac.serviceCreateVisitor = function(visitor) {
        return $http({
            url: '/Visitor/CreateVisitor',
            data: { visitor: visitor },
            method: 'post'
        });
    }

    return fac;
}])

Answer №1

The error is correct because you are overwriting the function with a Promise in the following line.

$scope.actionViewVisitors = function () {
    $scope.actionViewVisitors = viewVisitorService.serviceViewVisitors() 
        .then(function (response) {
           $scope.visitorList = response.data.visitorList;
        });
}

To fix this, simply remove $scope.actionViewVisitors =

$scope.actionViewVisitors = function () {
    viewVisitorService.serviceViewVisitors() 
        .then(function (response) {
           $scope.visitorList = response.data.visitorList;
        });
}

Answer №2

When you make the initial call to this function, it transitions from a basic function to a Promise. Perhaps your intention is to directly return the result instead?

$scope.actionViewVisitors = function () {
    return viewVisitorService.serviceViewVisitors()
        .then(function (response) {
        debugger;
            $scope.visitorList = response.data.visitorList;
        });
}

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

"Ng-repeat function seems to be malfunctioning, although I am able to view

There seems to be an issue with ng-repeat when dealing with an array of objects: dummy.json [ {"name":"alpha", "data":[{"name":"Unit 1", "prereqs":[]}]}, {"name":"beta", "data":[{"name":"Unit 1", "prereqs":[]}]} ] While I am able to fetch the total ...

Input text into search box to transfer value to URL without using the equal (=) symbol

Currently, my website allows users to search by entering a value in the URL after /search/. For instance, searching for "hello" can be done by visiting www.mywebsite.com/search/hello. Now, I am looking to implement a simple search box that functions simil ...

Adjust the size of a div element dynamically to maintain the aspect ratio of a background image while keeping the

Utilizing the slick slider from http://kenwheeler.github.io/slick/ to display images of varying sizes, including both portrait and landscape pictures. These images are displayed as background-image properties of the div. By default, the slider has a fixed ...

What is the best way to eliminate an element from a nested array within an array using Ionic 4?

I'm looking to remove a specific item from an array called myItemsList. Let's say the first array in myItemsList contains only one item, which is "First Item," and I want to delete it. myItemsList = [["First item"],["2"],["3"],["4"],["5"],["6" ...

Viewing information from the database without the need to refresh the page

HTML <textarea>Enter your question here</textarea><button class="askButton">SUBMIT</button> Upon clicking the button, the question is stored in the database using Ajax, jQuery, and Laravel. However, the question only appears after ...

Generate interactive text fields on button click event and store the information in a database

I'm currently working on a project that involves creating dynamic textboxes using PHP and jQuery. The goal is to submit a paper for presentation, where each presentation has multiple authors and each author has more than one affiliation. I've tri ...

Issue with resizing Ionic carousel when making an $http request

In my Ionic project, I am utilizing a plugin to create a carousel (https://github.com/ksachdeva/angular-swiper). The demo of this plugin includes a simple repeat function. However, when I replaced the default repeat with my own using $http, it caused an is ...

What is the method used to create the scrolling effect on this website?

I am in the process of creating my own personal website and I would like it to function similar to the following example: Instead of the typical scrolling, I'm interested in transitioning between different sections on the page. Could this be achieved ...

Troubleshooting problem with autoplay on a Parallax Content Slider in IE8

Does anyone know how to hide the arrows on pictures in IE8 when the mouse is not hovering over them? I've been struggling to find a solution and would really appreciate some help. ...

jQuery autocomplete feature is not functioning properly on dynamically generated input fields

I am encountering an issue with autocomplete on dynamically created fields. In the image attached, I have created dynamic fields by clicking on the plus sign. Autocomplete is working on the first row, but for the rest of the dynamically generated rows, au ...

Determining the cursor's location within an editable paragraph in WKWebView on iOS devices

Is it possible to retrieve the cursor's position in a WKWebView on iOS when there is an editable paragraph (a paragraph with contentEditable set to true) present? UPDATE: Adding more details, the editable div may contain other subnodes as well. ...

Adding data from a database into an object in PHP for temporary use during the loading process can be achieved by following

I'm a beginner in PHP and I have some code that retrieves category type data from a database. I want to temporarily store this data in a PHP object while the page is loading. Initially, I need to load all predefined data and then use it when a certain ...

A valid ReactComponent must be returned in order to properly render in React. Avoid returning undefined, an array, or any other invalid object

While working on my react application, I came across an error that I have been trying to troubleshoot without any success. It seems like I must be overlooking something important that could be quite obvious. *Error: VideoDetail.render(): A valid ReactComp ...

What is the best way to add a new div element as a sibling to the initial div created with d3?

Essentially, my goal is to insert a new div after another div: not as a child of the first div, but rather as a sibling. When I use the following Code, it results in a div nested inside an h4 tag :( let content = d3.select('#id_') let divs = co ...

A more cost-effective method to replicate an image multiple times using Angular

In the productivity tool I've created, there is a daily log of pomodoros completed. Each day's progress is displayed on a timeline with a tomato icon representing each pomodoro. To achieve this visual representation, I am using AngularJS directiv ...

What steps can be taken to restrict a user's access to a route through URL parameters?

I am currently developing an Express application that generates and exports a document based on the selections made by a user from two dropdown menus. The values selected in the dropdowns are passed as route parameters after the user clicks a button, trigg ...

Issue with conflicting versions in Bower dependencies

Just starting out on an angular project and incorporating bower. I've added two packages with --save to update my bower.json file. After running bower update, this is the result I get: Please take note that, ng-token-auth#0.0.29 requires an ...

Using React JS to invoke PHP script upon onClick event

Struggling to figure out the process of calling a PHP script through an AJAX call from a React JS script or when a submit button is clicked in the React component. It was a breeze with normal HTML and jQuery, but transitioning to React has proven challengi ...

Switch up the Position of a Frame with jQuery

I'm attempting to cycle through an array of URLs in order to designate them as locations for a frame. The current setup I have can be found on this fiddle: var l = ['0', '1', '2', '3', '4', '5&ap ...

Dynamically generated input fields using jQuery

Here is the code I'm using to dynamically add and remove input fields: I've encountered two issues that I haven't been able to resolve: $(wrapper).append('<div><input type="text" name="mytext[]"/><a href="#" class="remo ...