AngularJS - Issue with NgView functionality

Here is the basic setup, with a default noemployee.html partial set as the ng-view

Index.html content:

 <div id="container" ng-controller="EmployeeCtrl">

 <!-- Side Menu -->
 <span id="smenuSpan">
 <ul id="thumbList">
 <li ng-repeat="employee in employees | filter:categories">
 <a href="Employee/{{employee.id}}"><img  class="smallImage" ng-src="content/app/images/{{employee.image}}" alt="{{employee.description}}"></a>
 </li>
 </ul>
 </span>

 <!-- Content -->
 <span id="contentSpan">
 <div ng-view></div>    
 </span>

 </div>

My Route Provider:

var EmployeeModule = angular.module('EmployeeModule',  [], function($routeProvider, $locationProvider) {

$routeProvider.when('/', { templateUrl: 'content/app/partials/noemployee.html', controller: EmployeeModule.EmployeeCtrl });
$routeProvider.when('Employee/:id', { templateUrl: 'content/app/partials/employee.html', controller: EmployeeModule.EmployeeCtrl });
$routeProvider.otherwise({ redirectTo: '/' });

$locationProvider.html5Mode(true);

My Controller:

function EmployeeCtrl($scope, $http, $routeParams, $timeout) {

    $scope.employees = [
{ "id": 1, "category": "ones", "image": "person1.jpg",  "description": "person 1 description", name:"Jane Smith" },
{ "id": 2, "category": "twos", "image": "person2.jpg", "description": "person 2 description", name: "Mark Sharp" },
{ "id": 3, "category": "threes", "image": "person3.jpg", "description": "person 3 description", name: "Kenny Suave" },
{ "id": 4, "category": "fours", "image": "person4.jpg", "description": "person 4 description", name: "Betty Charmer" },
{ "id": 5, "category": "fives", "image": "person5.jpg", "description": "person 5 description", name: "John Boss" }
];

$scope.employeesCategories = [];
$scope.currentEmployee = {};
$scope.params = $routeParams;

$scope.handleEmployeesLoaded = function (data, status) {
    //$scope.images = data;
    // Set the current image to the first image in images
    $scope.currentEmployee = _.first($scope.employees);
    // Create a unique array based on the category property in the images objects
    $scope.employeeCategories = _.uniq(_.pluck($scope.employees, 'category'));
}

$scope.fetch = function () {
    $http.get($scope.url).success($scope.handleEmployeesLoaded);
};

$scope.setCurrentEmployee = function (employee) {
    $scope.currentEmployee = employee;
};

// Defer fetch for 1 second to give everything an opportunity layout
$timeout($scope.fetch, 1000);

}

Observations:

  1. When clicking on an employee, no 'Employee/??' is added to the address bar path, and the main content div does not change the partial to the employee.html.

  2. If "$locationProvider.html5Mode(true);" commented out, the default localhost changes to "http://localhost:31219/#/", resulting in a 404 error page when clicking on any employee.

There seems to be a simple solution that I am overlooking.

Goals:

  1. Avoiding hash tags in the address bar is preferred.
  2. It would be nice to hide the employee ID from the address bar, although this may affect the functionality of changing the partial without it.

  3. The partial should switch to the 'employee.html" page when an employee is clicked.

Any insights on what might be going wrong here?

Thank you in advance!

Answer №1

Resolution:

  1. I made the necessary adjustment to the img href by adding '#/' --> href="#/Employee/{{employee.id}}"
  2. I decided to comment out '$locationProvider.html5Mode(true);'

On a related note, I really wish there was a way to make this work without using those bothersome hash tags. Any suggestions?

To enable html5mode, your server must serve the main app index file for routes that would otherwise be invalid.

For instance, if your backend code handles operations on paths like: /api/employees, /api/employees/:id, etc...

and serves static content such as images, html, css, js, etc.

In case of any other request that would result in a 404 error, it should respond with a 200 code and return the index.html file instead.

This approach ensures that any non-static and non-server side route is managed by the Angular application.

You can find information about this in the Angular guide on this page: http://docs.angularjs.org/guide/dev_guide.services.$location

Note the 'server side' remark at the end:

Html link rewriting

When using HTML5 history API mode, links may need to be different for various browsers, but you can simply specify regular URL links like:

<a href="/some?foo=bar">link</a>

Upon clicking the link:

In an older browser, the URL changes to /index.html#!/some?foo=bar

In a modern browser, the URL changes to /some?foo=bar In certain situations, links are not rewritten; instead, the browser will perform a full page reload to the original link.

Links containing target element Example:

<a href="/ext/link?a=b" target="_self">link</a>

Absolute links going to a different domain Example:

<a href="http://angularjs.org/">link</a>

Links starting with '/' leading to a different base path when base is defined
Example:

<a href="/not-my-base/link">link</a>

Server side

Using this mode requires URL rewriting on the server side, where all links need to be redirected to the entry point of your application (e.g. index.html)

Answer №2

The issue at hand was:

<a href="Employee/{{employee.id}}"><img  class="smallImage" ng-src="content/app/images/{{employee.image}}" alt="{{employee.description}}"></a>

Resolution:

  1. I realized that I needed to add '#/' in the img href --> href="#/Employee/{{employee.id}}"
  2. I decided to comment out '$locationProvider.html5Mode(true);'

On a side note, I really wish there was a way to make this work without using those troublesome hash tags. Any suggestions from anyone?

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

The Iframe on the webpage is automatically refreshing once a submission is made, which is not a feature present in the original version of

Within my newsletter.html file, I have set up a newsletter where users can submit their email addresses, which are then stored in my JSON file. In homepage.html, I embedded an iframe from the newsletter.html file. Everything seems to be working fine, exce ...

Mastering sorting in AngularJS: ascending or descending, the choice is yours!

I have set up a table view with infinite scroll functionality. The table contains 2000 objects, but only shows 25 at a time. As the user scrolls to the bottom, it loads an additional 25 elements and so on. There is a "V" or "^" button in the header that sh ...

Using jQuery to access the value of the CSS property "margin-left"

I created a JavaScript game with moving divs that have different transition times. The game includes a function that is called every 1/100 seconds, which checks the position of the divs using: $("class1").css("margin-left") Here's the strange part: ...

Is there a way to determine the number of syllables in text as it is being typed?

Working on a React-based web app, I am trying to determine the number of syllables in a textarea as the user types. Encountering errors like "cannot find length of a null" at every turn. Right now, all I want is to utilize console.log() for troubleshooti ...

Link up each query with every php echo

Suppose I have the following PHP code: $logger = $_SESSION['logger']; $postquery = $con->query("SELECT * FROM posts ORDER BY id DESC LIMIT 5"); while($row = $postquery->fetch_object()){ $posts[] = $row; } And then, this section of ...

Implementing watch functionality with array in Vuejs for bidirectional communication between parent and child components

Here is a simplified version of a parent component I created: // parent component <template> <layout v-for="(value, idx) in array" :pickUpLength="array.length" :idx="idx" :key="idx" > <button @click="addArray">a ...

Comparing Angular 2 with Angular.js, React.js, and Typescript

Hello there, I am a fresh-faced web developer looking to create a modest website for my personal use. However, my knowledge is limited when it comes to JavaScript and jQuery concepts. In order to expand my skills and build an enhanced website, I decided ...

exposing an AngularJS service property to the $scope object

I am attempting to make an angular service property accessible to $scope in order to use it in the view. My code is structured as follows: /**API Post SERVICE for user login*/ function login(username,password){ return $http.post('/api/login/&apos ...

"In the most recent version of THREE.js (r82), the shadow is not detectable

I am having trouble casting a shadow from a cube onto a plane using MeshLambertMaterial in my code. Despite setting up the scene correctly, the shadows are not appearing as expected. Most solutions I have come across suggest that objects should be within ...

What causes the failure of $event binding when using RowGroup tables with PrimeNG?

I have successfully implemented RowGroup to store 3 different tables, which is working great. However, I am facing an issue with the onRowSelect function not functioning properly. When I click on any row of the RowGroup tables, nothing happens. On another ...

Standardizing URLs with ExpressJS router

Seeking normalized/canonical URLs for a single page application running on an ExpressJS server. While the SPA is supported by a server-side router, templates can vary slightly for different app URLs. One particular difference is the presence of the <li ...

Displaying JSON data with dynamic color changes in an HTML table: A comprehensive guide

Scenario: I am currently working on a project where I need to fetch data from an external json file, parse it, and then dynamically add it to an HTML table using the footable jQuery plugin. Question: I have a query regarding how to use JavaScript to parse ...

When I hover over one div within another div, JavaScript triggers the "onmouseover" and "onmouseout" events

I'm currently developing a grid layout for my upcoming website. Here is the PHP code snippet I'm working on: echo"<div class='model_container_invisible' onMouseOver='fade(this, 0)' onMouseOut='fade(this, 1)'>" ...

"Trying to refresh your chart.js chart with updated data?”

Greetings! I have implemented a chart using chart.js and here is the corresponding code: let myChart = document.getElementById('myChart').getContext('2d'); let newChart = new Chart(myChart, { type: 'line', data: { labels: ...

Incorporate a polygon or circle shape seamlessly into the surrounding Google Map environment

Currently, I have a circle created using maps.Polygon in my code. By setting the strokeWeight to 0, I can remove the outline of the polygon. Is there a way to blend the circle seamlessly into the map so that the transition between the circle and the rest o ...

Is it possible to access the package.json properties within a module executed by npm?

My task is to develop a module that will run from a "scripts" property in the user's package.json, like so: "scripts": { "runMyModule": "mymodule -stuff stuff" } PLEASE NOTE: This is not referring to my module's own package.json, but rather ...

Error encountered: A missing semicolon was detected before a statement while executing code within a for

Although this question may have already been asked, I am struggling to understand why it is not working as expected. I simply want to increment the markers array within a for loop and then add each marker to the vector source using vectorSource.addFeature ...

What is the best way to run a function after 10 seconds of inactivity using jquery?

Can anyone help me figure out how to run a function every 10 seconds when the system is idle? Here's an example: setInterval(function () { test(); },10000); //for every 10 Sec I really need assistance in getting this function to ...

Create a Discord.js bot that automatically deletes any URLs that are posted in the server

Seeking advice on how to have my bot delete any URLs posted by members. I am unsure of how to accurately detect when a URL has been shared, especially since they can begin with https, www, or some other format entirely. Any insights would be greatly apprec ...

The removal of a JQuery element can result in causing the webpage to become unresponsive and lead to

When attempting to create a loop in JQuery to remove elements from my HTML, I encountered an issue where the function caused my browser to hang and become unresponsive. Here is the JQuery code I used: function removeElement(){ var i =0; ...