Error: The variable lecturerFac has not been declared

Upon loading the html page, my controller fetches data from an API endpoint related to a course. The page is then populated with the course data. However, I also want to display information about the lecturer of the course (such as their image, name, description, etc.). I attempt to pass the lecturer's name to the method using the ng-init directive, but encounter a ReferenceError: lecturerFac is not defined.

I suspect that the issue lies in how I am calling the getLecturer() function using the ng-init directive.

My goal is to have both the course details and the lecturer's details displayed on the page when it loads.

courses.html

<div class="container"  ng-controller="CoursesDetailsCtrl">

    <div class="row" >
        <div class="col-4" ng-model="getLecturer(courses.lecturer)">
           <div>
             <h3>{{lecturer.name}}</h3>
             <<div>
                 <img class="img-circle"  ng-src="{{lecturer.picture}}" alt="" /> 
             </div>
                <p>{{lecturer.description}}</p>  -->
           </div>

        </div>
        <div class="col-8"> 
            <div class="myContainer" >
                <h2>{{courses.name}}</h2>
                <div class="thumbnail">
                    <img  ng-src="{{courses.picture}}" alt="" /> 
                </div>
                <div>
                    <p>{{courses.description}}</p>
                </div> 
            </div>
        </div> 
    </div>
</div>

CoursesDetailsCtrl

todoApp.controller('CoursesDetailsCtrl', ['coursesFac','lecturerFac','$scope','$stateParams', function CoursesCtrl(coursesFac, lecturerFac, $scope, $stateParams){

$scope.getLecturer = function(name){
        lecturerFac.getLecturerByName(name)
            .then(function (response) {
                $scope.lecturer = response.data;
                console.log($scope.lecturer);
            }, function (error) {
                $scope.status = 'Unable to load lecturer data: ' + error.message;
                console.log($scope.status);
            });
    };

}]);

lecturerFac

todoApp.factory('lecturerFac', ['$http', function($http) {

var urlBase = '/api/lecturer';
    var coursesFac = {};

     lecturerFac.getLecturer = function () {
        return $http.get(urlBase);
     };

    lecturerFac.getLecturerByName = function (name) {
        return $http.get(urlBase + '/' + name);
    };

    return lecturerFac;
}]);

Answer №1

todoApp.factory('teacherFactory', ['$http', function($http) {

    var baseURL = '/api/teacher';
        var coursesFactory = {};
        var services = {};
         services.getInstructor = function () {
            return $http.get(baseURL);
         };

        services.getInstructorByName = function (name) {
            return $http.get(baseURL + '/' + name);
        };

        return services;
    }]);

Answer №2

The reason behind this error could be that the lecturerFac variable is not initialized in the factory. To fix this, create an empty object called lecturerFac in the factory and make sure to return it.

todoApp.factory('lecturerFac', ['$http', function($http) {
    var urlBase = '/api/lecturer';
    var coursesFac = {};

    var lecturerFac= {};/////////////////////

    lecturerFac.getLecturer = function() {
        return $http.get(urlBase);
    };
    lecturerFac.getLecturerByName = function(name) {
        return $http.get(urlBase + '/' + name);
    };
    return lecturerFac;
}]);

Additionally, refrain from calling functions inside ng-model. When binding with ng-model, ensure that it is accessible for both reading and writing, such as a property/field on an object. Consider using ng-init instead.

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

When saving, generate a new object and send it to the designated endpoint

I'm feeling a bit confused, unsure of how to proceed. In my program, the task is to upload images (in base64 format) and add them to an array with a maximum limit of 5. After uploading the images, the next step is to click a button labeled Save to s ...

Tips for transferring and retrieving information with an express backend server

Here is the front-end code snippet: export default async function get(){ let res = await fetch('http://localhost:4000/data/'); console.log(res.json()); } And this is the back-end code snippet: const scraper = require('./scraper.js&a ...

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 ...

Receiving data from multiple sockets in Node.js with Socket.io

I recently started working with Node.js to develop an online game that acts as a server-side application. This application serves the .html and .js files to the client while managing the game's logic. I'm utilizing Socket.io for communication bet ...

Mirroring the content of one canvas element onto a separate remote canvas element

I'm working on an app that will connect two users, A and B, allowing them both to see a canvas element (used as a paint console) on their respective screens. When one user draws something on their canvas, the other user's canvas will reflect the ...

jQuery compatible JavaScript plugin

Currently, I am in the process of developing a JavaScript plugin. My goal is for it to make use of jQuery functionalities, while also gracefully degrading if jQuery is not present on the page. For instance, jQuery users would initiate a slideshow by calli ...

When attempting to invoke the rest function, an error occurs stating that the dataService.init in Angular is not

Learning AngularJS has been my current focus. To practice, I have been working on a Quiz app tutorial. However, I encountered an issue when trying to call the rest function of a factory after injecting it into one of my controllers. The JSON data for this ...

Creating an AngularJS directive that utilizes a switch statement based on the value of an attribute

I have a specific directive that is assigned one of 13 different types as an attribute. Based on the type, the directive will render various HTML elements corresponding to that type. The type value remains constant and does not change once the directive is ...

The jQuery .each function is malfunctioning specifically on Google Chrome browsers

I developed a web application that utilizes jQuery to automatically submit all forms on the page. The code snippet is as follows: $('form').each(function() { $(this).submit(); }); While this functionality works perfectly in Internet Explore ...

Steps for selecting checkboxes according to database values in AngularJSWould you like to learn how to automatically check checkboxes based on the

I am experiencing an issue where I can successfully insert values into the database based on what is checked, but I am encountering difficulty retrieving the values when fetching from the database. Can anyone provide me with some assistance? Thank you. Th ...

Issues encountered transferring data using wp_localize_script

I need help passing PHP data to a JavaScript script in my project. To achieve this, I am utilizing the wp_localize_script function. wp_register_script('googlechart', 'https://www.gstatic.com/charts/loader.js'); wp_register_script(&apos ...

Tips for linking JSON data with a variable in an AngularJS controller

Json Data { "TotalRecordCount": 50, "Results": [ { "TestId": 5002, "TestName": "Test 01/05/2016" } ] } Service Example function fetchTestData() { var deferred = $q.defer(); $http.get(TestAppConfig.TestApiRo ...

Utilizing Async.each fails to trigger the ultimate callback function

Here's the scenario: I expect the function finalCallBack to be triggered after we finish looping through all elements. var rows = [ { name: 'first'}, { name: 'second'} ]; var execForEachRow = function(row, callback){ var ...

"Troubleshooting: Unable to Trigger jQuery Click Event Using Class Selector

I have two separate lists with different classes, <li><a href='#' class="cls1" name="X">blah</a></li> <!-- Click to load a cls2 item --> <li><a href='#' class="cls1" name="Y">blah</a>< ...

The value retrieved from redux appears to be varying within the component body compared to its representation in the return

Trying to fetch the most recent history value from the redux store to pass as a payload is presenting a challenge. When submitting a query, the history updates and displays the latest value within the map() function in return(), but when checking at // CON ...

Angular Service provides String as a dictionary format for retrieval

My service is defined as: angular.module('inviteService', ['ngResource']).factory('Invite', function ($resource) { return $resource('/invite'); }); The controller looks like this: $scope.invite = function ...

Utilizing props for toggling the navigation list, incorporating nested arrays or objects

My issue involves two components that are loading data. I want the links to be output like this: group1 linka linkb However, they are currently displaying like this: group1 linka group1 linkb I believe the problem lies in how I am handling the ...

Node.js HTTP request not returning any content in the body/message

Having some trouble with the requestjs package as I attempt to post data and receive a response. No matter what I do, the body response always ends up being undefined. const request = require('request'); request({ method: "POST", ...

Expression fragment in Thymeleaf

In splitting my templates into head/main/footer parts using thymeleaf, I have found a method to include stylesheets and javascript on certain pages while excluding them from others. This is achieved through the use of fragment expressions outlined here. M ...

Synchronizing Browser with Gulp and Ghost Blog for seamless integration

Currently, I am managing a Ghost blog by simply starting it with the command: npm start After starting, the blog should be running on http://lolcahost:2368 In my gulpfile, I have set up browser sync to run like this: gulp.task('default', funct ...