Looking to spice up your website by incorporating a menu and setting up navigation throughout your pages using AngularJS?

Here is a snippet of HTML code that allows users to enter a movie title and displays search results. I am looking to add a menu to this page, with links redirecting to different pages such as 'About Us', 'Featured Films', and 'Search Films'.

My goal is to implement the ngRoute feature in Angular to navigate to these pages.

Below is the HTML and JS code I have so far. The JS file currently fetches movie data from the OMDB API, but I want to include ngRoute functionality in my JavaScript.

<!doctype html>
<html>

<head>
  <link rel="stylesheet" href="style.css" />
  <script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>


  <!-- SPELLS -->
  <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.25/angular.min.js"></script>
   <!-- SCROLLS -->
  <link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" />
  <link rel="stylesheet" href="//netdna.bootstrapcdn.com/font-awesome/4.0.0/css/font-awesome.css" />

  <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.0-beta.1/angular-route.js"></script>
  <script src="script.js"></script>
  <title>Movie Search | OMDb API</title>
</head>

<body ng-app="OMDbAPISearch">
  <div class="container" ng-controller="searchMovies">

    <h1>Search a Movie Title Below</h1>
    <p>This application utilizes OMDb API data for all results (<a href="http://www.omdbapi.com" target="_blank">http://www.omdbapi.com</a>)</p>
    <form>
      <div class="search">
       <input id="theSearch" ng-model="searchparam" placeholder="movie name" type="text" ngTrim="true" />
       <button ng-click="fetch()">Search</button>
       <div class="clear"></div>
      </div>
    </form>

    <div class="results">

      <div class="result" movie-srch-results ng-repeat="movie in movieResults"></div>

    </div>
    <div class="noResults"></div>

  </div>
</body>

</html>

I would like to incorporate ngRoute into my JavaScript file through a new menu called 'Pages' featuring options like 'About Us', 'Features Films', etc.

Any assistance on integrating ngRoute into my JS file would be greatly appreciated.

(function(angular) {
  'use strict';
  angular.module('OMDbAPISearch', [])
    .controller('searchMovies', ['$scope', '$http',
      function($scope, $http) {
        $scope.method = 'GET';
        $scope.fetch = function() {
          if ($scope.searchparam) {
            $scope.url = 'https://www.omdbapi.com/?s=' + $scope.searchparam + '&type=movie&r=json';
            $http({
              method: $scope.method,
              url: $scope.url
            }).
            then(function(response) {
              if (response.data.Response) {
                // success
                $('.results').css('display', 'block');
                $('.noResults').css('display', 'none');
                var theSrchResults = response.data["Search"];
                angular.forEach(theSrchResults, function(obj) {
                  // loop through each movie, and pull the details using the IMDB ID
                  $http({
                    method: $scope.method,
                    url: 'https://www.omdbapi.com/?i=' + obj.imdbID + '&plot=full&r=json&tomatoes=true'
                  }).
                  then(function(response) {
                    // extend the details to the parent
                    obj.details = response.data;
                  });
                });
                $scope.movieResults = theSrchResults;
              } else {
                //error, movie not found
                console.log("not found");
                $('.results').css('display', 'none');
                $('.noResults').css('display', 'block');
                $('.noResults').html("<strong>No results found.</strong>");
              }
            }, function(response) {
              console.log("failure");
              $('.results').css('display', 'none');
              $('.noResults').css('display', 'block');
              $('.noResults').html("<strong>Network or data error, please try again.</strong>");
            });
          } else {
            // no input value
            $('.results').css('display', 'none');
            $('.noResults').css('display', 'none');
            $('#theSearch').fadeIn(100).fadeOut(100).fadeIn(100).fadeOut(100).fadeIn(100);
          }
        };
      }
    ])
    .directive('movieSrchResults', function() {
      return {
        templateUrl: 'movieResults.html'
      };
    });
})(window.angular);

If anyone has guidance on how to integrate ngRoute into my JS file, please reach out. Thank you!

Answer №1

Simply make the necessary adjustment to your line of code

angular.module('OMDbAPISearch', [])
by changing it to
angular.module('OMDbAPISearch', ['ngRoute'])
. Then, insert the following lines below it:

angular.module('OMDbAPISearch', ['ngRoute'])
.config(function($routeProvider,$locationProvider,$httpProvider) {
    $locationProvider.html5Mode(true);
    $routeProvider
    .when('/',{
        templateUrl:  'home.html'
    })
    .when('/home',{
        templateUrl: 'home.html'
    })
    .when('/about',{
        templateUrl: 'about.html'
    })
    .otherwise({
    redirectTo: "/"
    });
})

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

Set my browser to flash as a signal

One of my colleagues developed an efficient MVC chat application for our team to discuss work matters without having to step away from our desks. I'm looking for suggestions on how we can alert each other when a new message has been sent. I was think ...

Exploring the capabilities of angular.element for identifying and iterating through various elements

As I work on a directive in AngularJS, I'm faced with the task of finding and iterating over all the controls within a form. If jQuery were available, the process would be simple: var inputs = element.find(".ng-invalid,.ng-valid"); inputs.each(funct ...

Stop the form from refreshing upon submission using an Ajax call in AngularJS

Currently, I am in the process of developing a search form that requires two inputs: Job title and Location. These keywords are used to gather data from various websites. However, upon submitting the form, the page refreshes itself. To prevent this, I have ...

Ensure that a div is both opened and closed after every specified "x" element

If you have 8 items in an array and want to display them with 3 items per page, resulting in a total of 3 pages, there is a simple logic involved. However, using ng-repeat to achieve this may not be straightforward. If there isn't a direct method, alt ...

sending a POST request with fetch

When it comes to making AJAX requests, I used to rely on jQuery in the past. However, with the rise of React, there is no longer a need to include the entire jQuery library for this purpose. Instead, it is recommended to use JavaScript's built-in fetc ...

Failed to retrieve information from the Service for the component

My goal is to retrieve data from a service and display it in a component. Below is the code for my service: Service.ts export class PrjService { tDate: Observable<filModel[]>; prjData:Observable<filModel[]>; entityUrl; constructor(){ this ...

Enhance Laravel 5 by integrating browserify into the Elixir build process

My workflow for transforming coffee to js using browserify, browserify-shim, and coffeeify looks like this: I work with two main files: app.coffee and _app.coffee, designated for frontend and backend respectively. These files are located in resources/coff ...

The test suite encountered an error (EBUSY: resource busy or locked) and unfortunately failed to run at Nx version 14.5.10 and Jest version 27.5.1. It seems there was an

I have recently upgraded my NX Monorepo from version 13 to 14, and everything seems to be working fine except for the Jest migration. I keep encountering this error even after trying various solutions like clearing the cache, deleting node_modules, and rei ...

Testing the units of a system ensures that the flow and data storage are reliable

Currently, I'm facing an interesting challenge when it comes to unit testing and the flux data stores. Because the data stores are singletons that are only instantiated once (upon module import), any changes made during unit tests remain persistent. ...

What is the best way to empty a backbone collection in preparation for loading new data?

Hey everyone, I've been working on a Backbone application that involves adding and deleting or editing images. Currently, I'm using a router to navigate between different sections like the gallery and forms. However, whenever I make changes in th ...

Tips on minimizing the size of a data:image/png;base64 file in Javascript and Next.js

My project website is experiencing a significant decrease in performance due to the large number of images I am working with, resulting in warnings from Next.js. In order to optimize database storage and overall performance, I need to reduce the file size ...

Issues with displaying data in Angular ChartJS are troubling users

Currently utilizing Angular 6, my goal is to incorporate a Chart.js line chart. Essentially, I am fetching two arrays from my API: one named weight_data and the other named weight_date, which I then utilize for the chart. After receiving the arrays from t ...

Persistent breeze of EntityManager retains data despite completed server save process

I have been experimenting for a few days with integrating Breeze 1.4.9 with a rails backend in a non-traditional way compared to the Breeze Ruby SPA sample. Instead of making RESTful calls to the server every time an entity changes, I prefer to send bulk s ...

I keep getting a "Resource Not Found" error when using Angular's URL template

While working on my page, I encountered an error message related to pagination implementation: angular.min.js:87 GET http://localhost:56485/Areas/EVerify/Views/EVerify/dirPagination.tpl.html 404 (Not Found) My JavaScript file looks like this: var EVerif ...

Node.js does not support running Bootstrap and CSS, resulting in style not being applied due to the MIME type ('text/html') not being a supported stylesheet MIME type

I attempted to test out the Start Bootstrap Bare template using Node.js and Express. (Link to Start Bootstrap Template) I opted not to make any alterations to the HTML, CSS, and JavaScript files provided with the template. Instead, I created a new index.j ...

Using the Permissions directive in Angular

Currently, I am developing a Single Page Application (SPA) that interacts with a REST server on the backend. The objective is to create a user interface that is consistent across all roles. For example: On a product page, a guest can view the product and ...

Looping through two arrays simultaneously in Angular JS

Seeking help to display two arrays in a conversational manner using ng-repeat Let's say we have two arrays defined as follows: messages_send = ["hi","good, How about you?","cool","LOL","NFW"] messages_received = ["hey, How are you?","good, Thanks ...

Converting literal types within simulated JSON data

I'm currently working with a JSON object that looks like this: { "elements": [ { "type": "abstract" }, { "type": "machine" }, { "type": "user" ...

Specify the width of one element to always be the same as the width of another

One common challenge is maintaining the width of one element equal to another when the page loads (refer to link description here). However, it becomes tricky when the side width changes, such as resizing the browser window. Is there a way to dynamically ...

Using JavaScript to create a JSON object within a table

Currently, I am facing a challenge in creating a JSON object from an HTML table using JavaScript. While I can successfully retrieve the values of each cell in JavaScript, the issue lies in organizing and retrieving them as per my requirements. Here is the ...