The addition of ngRoute causes the controller in AngularJS to malfunction

Currently, I am attempting to implement routes in my angularJS application and have encountered an issue where integrating 'ngRoute' into the app causes the main controller to malfunction. Furthermore, I am experiencing difficulties with ngRoute not functioning as expected.

Here is a snippet of my code:

app.js (angular logic)

(function() {

    angular.module('fccNight', ['ngRoute'])

    .config(['$routeProvider', function($routeProvider) {

        $routeProvider

        .when('/', {
            templateUrl: 'results.html'
        })
        .otherwise({ redirectTo: '/' });

    }])




    //controllers
    .controller('mainController', ['$scope', '$http', function($scope, $http) {

        $scope.searchTerm = '';
        $scope.data = [];
        $scope.loading = false;
        $scope.goingNo = [];

        $scope.getResults = function() {
            if($scope.searchTerm !== '') {
                $scope.loading = true;
                $scope.data = [];
                $http.get('/api/search?term=' + $scope.searchTerm)
                    .success(function(results) {
                        $scope.loading = false;
                        $scope.data = results;
                        for(var i = 0; i < $scope.data.length; i++) {
                            $scope.goingNo.push($scope.data[i].going);
                        }
                    });
            }
        }

        $scope.addGoing = function(index) {
            // check if user is authenticated
            if($scope.data[index].going > $scope.goingNo[index]) {
                $scope.data[index].going -= 1;
            }
            else {
                $scope.data[index].going += 1;
            }
            // register in db
        }

    }])

})();

index.html's body:

<body ng-controller="mainController" id="mainController">





    <!-- CONTENT -->

    <div class="container">

        <div class="row text-center">

            <div class="col-xs-12 main">
                <h1>Where are you going tonight?</h1>
                <p>Find nearby pubs and RSVP ahead of time.</p>

            </div>

        </div>
        <div class="row">

            <div class="col-xs-12 col-sm-12 col-md-12 col-lg-8 col-lg-offset-2">

                <form>

                    <div class="input-group">
                        <input id="inputSearch" ng-model="searchTerm" type="text" class="form-control"  placeholder="Where are you?" autocomplete='off'>

                        <span id="goBtn" class="input-group-btn">
                            <a ng-click="getResults()" class="btn btn-default">Go</a>
                        </span>
                    </div>

                </form>

            </div>

        </div>

        <!-- LOADING -->
        <div class="row loading hidden" ng-show="loading">
            <div class="col-xs-12">

                <div class="loader"></div>

            </div>
        </div>

        <div class="text-center">Controller is working if search term is displayed: {{ searchTerm }}</div>


        <!-- TEMPLATE -->
        <div ng-view></div>


    </div>

    <!-- footer -->
    <footer class="row-footer">

        <div class="container">

            <div class="row">

                <div class="col-xs-12 text-center">

                    <a href="https://github.com/otmeek/fcc-night">
                        <i class="fa fa-github"></i>
                    </a> | 
                    <a href="https://www.freecodecamp.com">
                        <i class="fa fa-fire"></i>
                    </a> | built using the Yelp API
                </div>

            </div>

        </div>

    </footer>




    <!-- =====================SCRIPTS===================== -->
    <!-- jQuery -->
    <script src="//code.jquery.com/jquery-1.12.0.min.js"></script>
    <!-- Bootstrap -->
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS" crossorigin="anonymous"></script>
    <!-- AngularJS -->
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.3/angular.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/X.Y.Z/angular-route.js"></script>
    <!-- custom scripts -->
    <script src="js/app.js"></script>
    <script src="js/scripts.js"></script>
</body> 

results.html (the template I wish to load on the '/' route)

<p>Results are loading</p>
<div class="row result" ng-repeat="result in data">
    <div class="col-xs-12 col-sm-12 col-md-12 col-lg-8 col-lg-offset-2 result">
        <div class="row">

            <!-- image -->
            <div class="col-xs-3 col-sm-2">
                <div class="image">
                    <img ng-src="{{ result.image || 'img/noimage.jpg' }}">
                </div>
                <div ng-click="addGoing($index)" class="going text-center">
                    {{ result.going || 0 }} going
                </div>
            </div>


            <!-- text -->
            <div class="col-xs-9 col-sm-10">
                <h4><a ng-href="{{ result.url || '#' }}">{{ result.name }}</a> 
                    <small>{{ 'Rating: ' + result.rating || 'No rating available' }}</small></h4>
                <p>{{ result.text || 'No reviews for this establishment.' }}</p>
            </div>

        </div>
    </div>
</div>

Upon removing all routing logic from app.js and deleting ng-view from index.html while solely adding results.html, the application functions correctly. The controller loads properly, and everything operates seamlessly. However, upon introducing 'ngRoute' to the app, the results template fails to load, and access to any mainController variables or logic from index.html becomes unattainable.

If there are suggestions or insights into what might be causing this issue, please share your thoughts. Thank you!

Edit: A note that the cdn link for angular-route.js appears to be unavailable. Regrettably, I am unable to locate a download link for this library on the official site, and lacking bower, I am uncertain where to acquire this file.

Answer №2

To ensure proper functionality, update the version number in your index.html file for Angular route from X.Y.Z to a specific version like 1.4.8.

Modify the script tag as follows:

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-route.js"></script>

Instead of using:

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/X.Y.Z/angular-route.js"></script>

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

core.js encountered an issue at line 6210: TypeError - The function this.service.addDepartment does not exist

Whenever I attempt to click the 'Add' button on a web application that I'm constructing, an error pops up. core.js:6210 ERROR TypeError: this.service.addDepartment is not a function at AddEditDepComponent.addDepartment (add-edit-dep.componen ...

How can I create a hover effect animation in React?

I am looking to replicate the menu item underline animation demonstrated in this example. In jQuery, I would easily achieve this by obtaining the left position and width of a menu item, then using stop.animation on hover. Attempting this animation with R ...

What is the best way to call an Angular component function from a global function, ensuring compatibility with IE11?

Currently, I am facing a challenge while integrating the Mastercard payment gateway api into an Angular-based application. The api requires a callback for success and error handling, which is passed through the data-error and data-success attributes of the ...

Is there a way to make a button on a single div only affect that specific div

I have a PHP query that echoes a div for each row in the table. I want the div to slide up and then, when the user clicks the "read more" button, the div slides down. However, since it is echoed in a loop, all the divs have the same IDs and classes. I wo ...

Learn how to implement a conditional class binding in Vue 3, and discover how to apply additional classes when a specific condition is met

As a newcomer to Vue.js 3, I am wondering how to implement a conditional class binding in Vue 3. Specifically, I would like to achieve the following logic: if router.path != '/', then add the class 'nav-bar-two'; otherwise, do not apply ...

Embark on the journey of incorporating the Express Router

My Nodejs server is set up with router files that use absolute routes for the HTTP methods, such as /api/users/all. // /routes/user.routes.js module.exports = (app) => { app.use((req, res, next) => { res.header( "Access-Control-All ...

VueJS - Iterating over a list within a vue component causes the list to be empty

Having encountered an issue with the answers provided to my question from yesterday, I have decided to create a new query with additional details. To review the original question, please visit: VueJS - using mustache template strings inside href attribute ...

Unlocking the power of bitwise operations in VueJS with Javascript

Forgive me if this sounds like a silly question. I'm currently using vue-moment within my Vue.js application and I have the following code snippet: <!-- date = '2020-03-23 01:01:01' --> <span>{{ date | moment('from', & ...

Tips for showcasing a string value across various lines within a paragraph using the <br> tag for line breaks

I'm struggling to show a string in a paragraph that includes tags to create new lines. Unfortunately, all I see is the br tags instead of the desired line breaks. Here is my TypeScript method. viewEmailMessage(messageId: number): void { c ...

What is the approach for for loops to handle non-iterable streams in JavaScript?

In the realm of node programming, we have the ability to generate a read stream for a file by utilizing createReadStream. Following this, we can leverage readline.createInterface to create a new stream that emits data line by line. const fileStream = fs.cr ...

In the year 2021, eliminate linked documents using mongoose/MongoDB middleware

After extensive research on stack overflow, I attempted various solutions for deleting referenced documents in MongoDB using node.js. Unfortunately, most of them either utilize deprecated methods or simply do not function as expected. Within my applicatio ...

Is it possible to assign a different array to a variable in JavaScript?

I'm facing an issue with manipulating arrays in JavaScript within a function. This problem arises from an exercise found in the book Eloquent JavaScript, focusing on two specific functions: reverseArray(): designed to produce a new array that is the ...

The select2 ajax functionality encountered an error: Uncaught TypeError - Unable to access the 'context' property as it is undefined

Trying to make an AJAX request using the Select2 jQuery plugin. The query appears to be functioning properly, but the problem arises when ".context===undefined" is called on the "data" object: Uncaught TypeError: Cannot read property 'context' o ...

"I'm trying to incorporate react-datepicker into my ReScript application, but I'm struggling to

I am attempting to incorporate an external library like react-datepicker into my project. Below is the code snippet and how I am using it: module DatePicker = { @react.component @module("react-datepicker") external make: () => React.eleme ...

Adjusting attention to the switched element

I am currently developing an inline editing feature using AngularJS. Here is the code snippet from my Controller: $scope.toggleEditor = function(){ $scope.editorEnabled = !$scope.editorEnabled; //toggle editor view //struggling with this part $time ...

How to incorporate text into the white circle object using three.js

View the current state of my project on this JS Fiddle. I am looking to incorporate rotating text, whether in 3D or 2D. The text should rotate in sync with the white circle. I am open to any method that achieves the desired outcome. Below is the provided c ...

Connect-busboy causing NodeJS issue: TypeError - the method 'on' cannot be called on an undefined object

Recently I encountered an issue with a piece of my code: router.route("/post") .get(function(req, res) { // ... }) .post(authReq, function(req, res) { // ... // Get uploaded file var fstream; req.pipe(re ...

Managing consecutive synchronous side effects that are dependent on each other using React hooks

I am currently in the process of transitioning my application from using Redux to the new context and hooks, but I am facing challenges when it comes to handling a series of synchronous side-effects that rely on the response of the previous one. In my exi ...

Warning in Next.js: When utilizing conditional rendering, the server HTML is expected to have a corresponding <div> inside another <div>

Although similar questions have been asked on various platforms like Google, none seem to provide answers that align with my specific situation. Essentially, my goal is to have a different search bar displayed in the header based on the page I am currentl ...

Can JSON values be multiplied together?

Can you assign the value of a key in JSON by using the result of multiplying/adding two variables, values, strings+number, or strings+strings? Is this feasible? For example: { "string": "600*"+40 } ...