angularjs issue with displaying content in ui-view element

I am currently following a tutorial on the MEAN stack to gain familiarity with it. I have reached the part where they introduce routing configuration using ui-router. Despite setting everything up as instructed, my page is not rendering anything in the <ui-view> element.

(it was working fine before adding the routing config)

Here is how my files are structured:

index.html:

<!DOCTYPE html>
<html>
<head>
  <title>Flapper News</title>
  <link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet">

  <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.10/angular.min.js"></script>
  <script src="http://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.10/angular-ui-router.js"></script>
  <script scr="indexHomeState.js"></script>
  <script src="indexController.js"></script>
  <script src="postsService.js"></script>
  <style> .glyphicon-thumbs-up { cursor:pointer } </style>
</head>
<body ng-app="flapperNews">

  <div class="row">
    <div class="col-md-6 col-md-offset-3">
      <ui-view></ui-view>
    </div>
  </div>


    <script type="text/ng-template" id='/home.html'>
      <div class="page-header">
        <h1>Flapper News</h1>
      </div>

      <div ng-repeat="post in indexCtrl.getPosts() | orderBy:'-upvotes'">
        <span class="glyphicon glyphicon-thumbs-up"
          ng-click="indexCtrl.incrementUpvotesForPost(post)"></span>
        {{post.upvotes}}
        <span style="font-size:20px; margin-left:10px;">
          <a ng-show="post.link" href="{{post.link}}">
            {{post.title}}
          </a>
          <span ng-hide="post.link">
            {{post.title}}
          </span>
        </span>
      </div>

      <form ng-submit="indexCtrl.addPost()"
        style="margin-top:30px;">
        <h3>Add a new post</h3>

        <div class="form-group">
          <input type="text"
            class="form-control"
            placeholder="Title"
            ng-model="indexCtrl.title"></input>
        </div>
        <div class="form-group">
          <input type="text"
          class="form-control"
          placeholder="Link"
          ng-model="indexCtrl.link"></input>
        </div>
        <button type="submit" class="btn btn-primary">Post</button>
      </form>
    </script>


</body>
</html>

routingConfig (indexHomeState.js)

angular.module('flapperNews')
.config('indexHomeState', indexHomeState);


indexHomeState.$inject = ['$stateProvider', '$urlRouterProvider'];

function indexHomeState($stateProvider, $urlRouterProvider) {

    $stateProvider
    .state('home', {
        url: '/home',
        templateUrl: '/home.html',
        controller: 'indexController as indexCtrl'
    });
    $urlRouterProvider.otherwise('home');


}

my angular app/controller declaration:

angular.module('flapperNews', ['ui.router'])
.controller('indexController', indexController);

indexController.$inject = ['postsService'];

function indexController(postsService) {
    var vm = this;
    vm.test = 'Hello world';

    vm.getPosts = postsService.getPosts;
    vm.addPost = postsService.addPost(vm.title, vm.link);
    vm.incrementUpvotesForPost = postsService.incrementUpvotesForPost;

}

post service

angular.module('flapperNews')
.factory('postsService', postsService);

function postsService() {
    var serv = this;
    var posts = [
      {title: 'post 1', upvotes: 5},
      {title: 'post 2', upvotes: 2},
      {title: 'post 3', upvotes: 15},
      {title: 'post 4', upvotes: 9},
      {title: 'post 5', upvotes: 4}
    ];
    function getPosts() {
        return posts;
    }
    function addPost(title, link) {
        if(!title || title === '') { return; }
        posts.push({
            title: vm.title,
            link: vm.link,
            upvotes: 0
        });
        vm.title = '';
        vm.link = '';
    }
    function incrementUpvotesForPost(post) {
        post.upvotes ++;
    }
    return {
        getPosts: getPosts,
        addPost: addPost,
        incrementUpvotesForPost: incrementUpvotesForPost
    }

}

Answer №1

Your code is almost perfect, but there are a few things you need to fix:

$urlRouterProvider.otherwise('home');

should be changed to

$urlRouterProvider.otherwise('/home');

Also, make sure to correct the spelling of src to scr in your indexHomeState.js file, as this could be preventing your JS files from loading properly.

Scripts

<script src="indexController.js"></script>

If you don't have an indexHomeState provider defined in your app, do not include it as a string inside the config block.

angular.module('flapperNews')
  .config(indexHomeState); //removed `'indexHomeState',` from config

Check out the Demo Plunkr for reference

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

Generating a vibrant list with the help of JSON and the power of jquery

JSON file { "subject": "title", "level": [ { "title":"Test1", "sub":[{ "title":"Test1 sub_1", "links":[{ "title":"Test1sub1.1link_title", "address":"linkAddress" },{ "title":"Test1sub1.2_link_title", "address":"linkAddress" ...

Determine the background hue of a specific element on a website

Looking for assistance with my testing automation - specifically, I need to determine the background color of a web element. While I can easily identify if the text is highlighted, I am struggling to find the background color. Any solutions or suggestions ...

Transforming Node-Red strings into payload titles

My array payload is structured as: msg.payload[index].temp. I have separated the array into individual parts to send them over MQTT. Now, I am working with msg.payload.temp and msg.parts.index. msg:{ payload:{ address: "e4:32: ...

Is it possible to use JavaScript to retrieve a client's bookmarks with their consent?

Is there a way to streamline the process of importing bookmarks to my server for users? Can I use JavaScript to automatically retrieve a user's bookmarks, or is that not possible due to security concerns in browsers? ...

I'm facing an issue here: the function this.props.onSave is not defined

One issue I am facing is that the save action is not functioning properly. Function to handle save : handleSave = () => { this.setState({ loading: true }) const { category } = this.state this.props.onSave(category) } Save action button ...

Include a description in the cell of the table

I am struggling with adding a small description below one of the columns in my three-column table. I have tried using Grid, but so far, nothing has worked for me. Can anyone provide assistance? To give you a better idea, I have highlighted the desired res ...

Retrieve the image (via copy and paste) directly from the web browser

When it comes to copying images in a browser like chrome, there are two methods available: copying the image itself and copying the address of the image. If I copy the image address and paste it using my Paste Image button, I can successfully retrieve the ...

Different Techniques for Defining Functions in an AngularJS Controller Using the controllerAs Method

When using the 'controller as' approach instead of $scope, I am encountering issues with method calling from HTML. My question is, how many ways are there to declare and call functions using this approach? First: (For executing something initial ...

AngularJS - Oops! Looks like we encountered an error: [$injector:modulerr]

I have a client-server application and I am facing an issue with this error message: "Uncaught Error: [$injector:modulerr]". Despite searching for solutions, none of them seem to be fixing the problem. Here is my client-side code: angular.module('m ...

Ways to verify the user's authentication status on the server end

Before displaying an HTML page, I need to verify user authentication. Here is a snippet from my server.js: const express = require('express'); var jquery = require('jquery'); var admin = require("firebase"); const app = expre ...

An Angular directive utilizing dual aliases

Is there a simple method to give a directive two distinct names? For example: app.directive(['directiveNameOne', 'directiveNameTwo'], function() {...}); I have created a directive that handles both radio buttons and checkboxes in th ...

Botpress Converse API: Events table in database displaying mixed up order of events

The problem only occurs with the Converse API; the Webchat functions correctly. Upon inspecting the database, it is apparent that the 'createdOn' timestamp for sequentially sent messages is identical, leading to the mixed-up order. For example: ...

What could be causing the error with VITE_ENV in my project?

I am currently working on a project and I'm looking to utilize VITE_ENV for accessing environmental variables in place of using dotenv, even though I already have the dotenv package installed. The example I followed can be found in vite's docume ...

I possess a dataset and desire to correlate each element to different elements

[ { "clauseId": 1, "clauseName": "cover", "texts": [ { "textId": 1, "text": "hello" } ] }, { "clauseId": 3, "clauseName": "xyz", "te ...

Vue-Router functions only on specific routes

While my vue-router correctly routes the URL for all menu buttons, it's not displaying each Vue component properly. You can see a demonstration here. Here is a snippet of my HTML (using Vuefy) <div class="navbar-start"> <a ...

Can using the jQuery.clone method impact other functions?

Assuming $dom is a jQuery element, can the following line be safely removed if a is not utilized thereafter? var a = $dom.clone(true,true); When using $dom.clone(false,false), it appears that there are no side effects. I believe this method doesn't ...

What is the process for converting a negative decimal number into hexadecimal format?

hex = Number(-59).toString(16) The hexadecimal value of -59 is -3b But it should actually be ffffffffffffffC5 Any assistance on this matter would be greatly appreciated! ...

Ways to manually change the history in angular.js

Currently, I am facing a challenge in removing the querystring (specifically an invitation token) from the URL without triggering a page redirect. Here is an example of what the URL looks like: example.com/?invitation=fooo In our project, we are using n ...

Issue with negative z-index in modal window has not been resolved

I'm currently trying to customize the radio button using my own CSS styles, but I've encountered an issue. For some reason, setting the z-index to -1 is not working when the radio button is within a modal. Below is the code snippet that I am wor ...

AngularJS - Changing Views with Templates

At the moment, I am changing my directives in the following manner. Within my directive: (function(){ 'use strict'; var controller = ['$scope', function ($scope) { }]; angular .module('moduleName' ...