From Beginner to Expert: Mastering AngularJS in Chapter 4

I've been diving into the sitepoint ANGULARJS: NOVICE TO NINJA book and I've hit a roadblock with the final example in chapter 4. In this application, the default angular ngRoute module is swapped out for the more robust Angular UI Router module. Despite my best efforts, I can't seem to get it functioning properly and I'm at a loss as to where I've gone wrong. Below you'll find the code for the index page, view1.html, and view2.html. Any assistance would be greatly appreciated.

 <!DOCTYPE html>
<html ng-app="myApp">

<head>
    <meta charset="utf-8" />
    <title ng-bind="title"></title>
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular.js"></script>
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular-route.js"></script>
    <script src="https://angular-ui.github.io/ui-router/release/angular-ui-router.min.js"></script>
</head>

<body>
    <h3>Chapter 4 - App 15a - {{title}}</h3>
    <ul class="menu">
        <li><a ui-sref="view1">view1</a></li>
    </ul>
    <div ng-view></div>

<script>
'use strict';

angular.module('myApp', [
                            'myApp.controllers',
                            'ngRoute',
                            //This is the dependency on ui.router module
                            'ui.router' 
                        ]
);

// .run() gets called when all the modules are loaded
angular.module('myApp').run(
    function($rootScope){
        $rootScope.title = 'Angular Routing - The Angular UI Router';
    }
);

// $stateProvider and $urlRouterProvider are from ui.router module
angular.module('myApp').config(
    function($stateProvider, $urlRouterProvider, $locationProvider){ 
        $stateProvider
            .state('view1', {
                                url: '/view1',
                                controller:'Controller1',
                                templateUrl:'/partials/view1.html'
            })
            .state('view2', {
                                url: '/view2/:firstname/:lastname',
                                controller:'Controller2',
                                resolve:{
                                            names:  function(){
                                                        return ['Misko','Vojta','Brad'];
                                                    } 
                                },
                                templateUrl: '/partials/view2.html'
                            }
            );

    // when no route match found redirect to /view1
    $urlRouterProvider.otherwise('/view1'); 

    $locationProvider.html5Mode(true);
});

angular.module('myApp.controllers', [])
    .controller('Controller1', function($scope, $location, $state) {
        $scope.loadView2 = function() {
            // the following activates state view2
            $state.go('view2', {
                                    firstname: $scope.firstname,
                                    lastname: $scope.lastname
                                }
            );
        } 
    }
);

angular.module('myApp.controllers')
    .controller('Controller2', function($scope, $stateParams, names){
        $scope.firstname=$stateParams.firstname;
        $scope.lastname=$stateParams.lastname;
        $scope.names=names;
});

</script>
</body>
</html> 

<!-- Contents of view1.html -->

    <p>
        First name: <input type="text" ng-model="firstname" style="border:1px solid black;" /> <br/>
        <br/>
        Last name: <input type="text" ng-model="lastname" style="border:1px solid black;" /> <br/>
        <br/>
        <button ng-click="loadView2()">Load View2</button>
    </p> 


<!-- Contents of view2.html -->



    <p>
        From View2.
        <ul>
            <li>First name: {{firstname}}</li>
            <li>Last name: {{lastname}}</li>
        </ul>

        Our additional users are:
        <ul>
            <li ng-repeat="name in names">
                {{name}}
            </li> 
        </ul>
    </p> 

Answer №1

Simply change the protocol from http to https, and your code should function correctly. Check it out here. Ensure to include the necessary views as needed.

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

Update1

I have added <div ui-view></div> in the index.html file, which was missing initially. You had used ng-view for ngRoute instead of ui.router.

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

In Safari, there seems to be an issue where multiple URLs are not opening when clicked on from an anchor

Is there a way to open multiple URLs in Safari with just one click using window.open? I tried it, but only one URL opens in a new tab while the others do not. The version of Safari I am using is 11.0.1. onclick="window.open('URL1','_blank& ...

What are the implications of storing data in the id attribute of an HTML element?

If I have a template where I need to loop and generate multiple div elements, each containing a button, how can I listen to clicks on these buttons individually? <div class="repeatedDiv"> <button class="reply-button"> </div> $(&apos ...

I am having trouble with the browser detection not accurately identifying the browser I am currently using

Currently, I am working on a JavaScript code that will simply display the name of the browser being used to view the web page. Despite me using Safari, none of the navigators seem to recognize it as the current browser. The information displayed in my brow ...

Using Angular Spinners without relying on the timeout function

Encountering an issue with the angular spinner. I have an update button integrated with spin and loading, but it needs to stop after saving data into the database without utilizing any timeout function. function assignLectureToSubject(subject) { ...

Manipulate JSON insertions and character replacements using JavaScript or Python

I have a JSON file that contains an array of 500 objects. The structure of each object is as follows: { "books":[ { "title":"Title 1", "year":"2012", "authors":"Jack ; George", }, { "title":"Title 2", "year":" ...

Utilizing node.js as a standalone web server application

I've developed a node.js-based web server (Javascript file) designed to serve a Javascript-integrated web page for controlling immersive sound on mobile devices. The server utilizes native modules for MIDI and pcap communication, along with express fo ...

Dilemma arises from conflicting javascript codes

Currently, I am developing a web application where the main page features a timeline that needs to update its content automatically. To achieve this, I am utilizing the setTimeOut function of JQuery to refresh the timeline every x seconds. In addition, th ...

Create a regular expression to validate the date format of a material design datepicker as MM/DD/YYYY

I attempted to validate the date format of md-datepicker as MM/DD/YYYY using a regular expression and md-error Here is the Regular Expression for accepting MM/DD/YYYY format: const DOB_REGEX = /^(?:(?:31(\/|-|\.)(?:0?[13578]|1[02]))\1|(?:( ...

Issue with radio button click function not working on IE and Firefox

I am working with a form that has multiple inputs and radio buttons. Within the form, there are Yes & No radio buttons. When the "Yes" radio button is selected, additional data slides down below. HTML: <div class="item seperator first clearfi ...

Passing data between components in Vue.js

I am currently in the process of creating an application using Laravel and Vue. I have a navbar set up, which currently looks like this: <template> <nav class="navbar"> <p>{{msg}}</p> </nav> </template> And I am im ...

Cheerio - Ensure accurate text retrieval for selectors that produce multiple results

Visit this link for more information https://i.stack.imgur.com/FfYeg.png I am trying to extract specific market data from the given webpage. Specifically, I need to retrieve "Sábado, 14 de Abril de 2018" and "16:00". Here is how I did it using Kotlin an ...

Countdown malfunction: wrong date displayed

Utilizing the Countdownjs library in my project is resulting in an incorrect day count. Incorporating AngularJS, here is the custom directive I've implemented for the countdown: .directive('tempoPercorrido', function($interval){ ret ...

Send the user back to the homepage without the need to refresh the page

When the user clicks "Okay" in my window.prompt, the code below opens a new tab. Is there a way to direct the user to the home page without opening a new tab? if (window.confirm("Do you really want to leave?")) { window.open("./Tutoria ...

Issue encountered with NextJS where the post request utilizing Bcrypt is not being recognized

In the process of developing a basic login feature using nextJS, I have successfully managed to save new usernames and encrypted passwords from the registration page. The login functionality is intended to be similar, but requires comparing the password st ...

Encountered an `EPIPE` error during the testing of a POST request with Jest

I have a simple server that is set up to handle POST requests and return a "413 Request entity too large" error if the request body exceeds the allowed size. During my testing with Jest, I've noticed that sometimes the correct error is returned, but m ...

Is it possible to display a upload progress indicator without using a specialized ajax uploader

I'm working on a Rails application that uploads large files (~300mb). Is there a way to incorporate a progress indicator without relying on a specific HTML5 uploader or installing the nginx server module? Can this be achieved simply with the standard ...

Confusion with Javascript callbacks - seeking clarity

I am having difficulty grasping the concept of callback functions. I know that they are functions passed as parameters to other functions. My assumption was that when a function is passed as a parameter, it would be recognized as a callback function and ex ...

Ensuring the integrity of forms and validating inputs in Angular

Creating a form for adding or editing users has its own set of challenges. When the page loads with existing data in formData, it indicates that an existing user is being edited and the fields need to be populated accordingly. On the other hand, if the pa ...

How to align an unordered list horizontally in HTML without knowing the number of items

I'm currently developing a web page that needs to display an unknown number of items using the ul/li HTML tag. Here are my requirements: The list should utilize as much horizontal space as possible The list must be horizontally centered, even if lin ...

Receiving the outcome of an asynchronous function in JavaScript

async function retrieveKey() { try { var key = await dec.awsDecrypt('dev-frontend') return key; } catch(err) { } } //calling the function const result = retrieveKey() In the code snippet above, there is an asynchronous ...