Why isn't my ng-view in Angular loading properly?

After countless hours of searching, the app's page still loads blank. The issue remains elusive despite using Angular 1.3.5 and Angular-route v1.2.28.

Below is the code snippet from index.html:

<html ng-app="myApp">
<head>
<script src="js/angulark.min.js"></script>
<script src="js/angular-routek.js"></script>
<script>
var myApp = angular.module('myApp', ['ngRoute']);

myApp.config(function ($routeProvider) {
$routeProvider
.when('/',
{
controller: 'MainController',
templateUrl: 'views/nameView.html';
})
.when('/cityView',
{
controller: 'MainController',
templateUrl: 'views/cityView.html';
})
.otherwise({ redirectTo: '/' });
});

myApp.controller('MainController', ['$scope', function($scope) {
$scope.customers = [
{ name: 'Andre Queiroz', city: 'Rio de Janeiro' },
{ name: 'Fulano', city: 'Sao Paulo'}, 
{ name: 'Beltrano', city: 'Curitiba' }
];

$scope.addCustomer() = function () {
$scope.customers.push( 
{ name: $scope.newCustomer.name, city: $scope.newCustomer.city } 
);
};
}]);
</script>
<title>Meu Aplicativo</title>
</head>
<body>
<div>
<!-- Placeholder for views -->
<div ng-view> </div>
</div>
</body>
</html>

This snippet represents nameView.html

<div class="container">
<div ng-controller="MainController">
<div>
<h2>View 1</h2>
Name: <input type="text" ng-model="filter.name"/>
</div>
<br />
  <ul>
   <li ng-repeat="cust in customers | filter:filter.name | orderBy:'city'">{{cust.name | uppercase}} - {{cust.city}}</li>
  </ul>
</div

<div>
<p>Customer name:</p>
<input type="text" ng-model="newCustomer.name" />
<p>Customer city:</p>
<input type="text" ng-model="newCustomer.city" />
<button ng-click="addCustomer()">Add customer </button>
<a href="#/view2">View 2</a>
</div>
</div>
</div>

The cityView.html mirrors the structure of nameView.html but excludes the addCustomer functionality. Initially structured into separate module files, the code has been consolidated into one file to troubleshoot.

Answer №1

There seems to be an error in the JavaScript code within index.html file. For the MainController, make sure to modify your code as follows:

$scope.addCustomer() = function () {
    $scope.customers.push( 
        { name: $scope.newCustomer.name, city: $scope.newCustomer.city } 
    );
};

Change it to:

$scope.addCustomer= function () {
    $scope.customers.push( 
        { name: $scope.newCustomer.name, city: $scope.newCustomer.city } 
    );
};

Ensure that you use $scope.addCustomer= instead of $scope.addCustomer()=.

Answer №2

Great job, you're on the right track. The majority of errors are related to syntax.

Error 1: Remove the ; from the templateUrl within $routeProvider.when()

Example: templateUrl: 'views/cityView.html'

Error 2: You can't have parentheses when creating a method like this $scope: For example, $scope.newfunction = function() {...}

<html ng-app="myApp">
    <head>  
        <script src="js/angulark.min.js"></script>  
        <script src="js/angular-routek.js"></script>
        <script>
            var myApp = angular.module('myApp', ['ngRoute']);

                myApp.config(function ($routeProvider) {
                    $routeProvider
                        .when('/',
                            {
                                controller: 'MainController',
                                templateUrl: 'views/nameView.html'                      
                            })  
                        .when('/cityView',
                            {
                                controller: 'MainController',
                                templateUrl: 'views/cityView.html'                      
                            })
                        .otherwise({ redirectTo: '/' });
                }); 

                myApp.controller('MainController', ['$scope', function($scope) {
                    $scope.customers = [
                        { name: 'Andre Queiroz', city: 'Rio de Janeiro' },
                        { name: 'Fulano', city: 'Sao Paulo'}, 
                        { name: 'Beltrano', city: 'Curitiba' }
                    ];

                    $scope.addCustomer = function () {
                        $scope.customers.push( 
                            { name: $scope.newCustomer.name, city: $scope.newCustomer.city } 
                        );
                    };          
                }]);        
        </script>
        <title>Meu Aplicativo</title>
    </head> 
    <body>  
        <div>
            <!-- Placeholder for views -->
            <div ng-view> </div>                
        </div>
    </body>
</html>

There are some HTML errors in your view. Ensure you validate your HTML properly.

Error: In line 11, you need to correct </div to </div>

Also, you don't need to add a controller since you already added it in your config:

Remove it from your view: Change from

<div
  ng-controller="MainController">
to <div>

It's not mandatory, but it's recommended

In your last line, there is an extra </div>, please remove it:

<div class="container">
    <div ng-controller="MainController">
        <div>
            <h2>View 1</h2>
            Name: <input type="text" ng-model="filter.name"/>
        </div>
        <br />
        <ul>
            <li ng-repeat="cust in customers | filter:filter.name | orderBy:'city'">{{cust.name | uppercase}} - {{cust.city}}</li>
        </ul>
    </div>

    <div>
        <p>Customer name:</p>
        <input type="text" ng-model="newCustomer.name" />
        <p>Customer city:</p>
        <input type="text" ng-model="newCustomer.city" />
        <button ng-click="addCustomer()">Add customer </button>
        <a href="#/view2">View 2</a>
    </div>
</div>

PS: Double-check your syntax errors. Tools like jshint, jslint, or Chrome Dev Tools / Firebug can be helpful. Consider setting up your editor (Sublimelinter for Sublime, for instance) to use jshint. Alternatively, use an IDE like Webstorm which includes these features.

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

Having trouble making radio buttons clickable with jQuery/JS?

Having a minor issue as a beginner, I am struggling to make buttons within a DIV clickable. The top line consists of 5 buttons that work perfectly. When clicked, a 2nd row appears as expected, but for some reason, I can't click on them. What could be ...

How can I define the upper limit for the axis on an AngularJS polar chart?

Is there a way to set the maximum polar axis value to 100, regardless of the data received? This is my current code in progress: angular.module("app", ["chart.js"]).controller("ChartCtrl", function($scope) { $scope.labels = ["January", "February", ...

issues arising from a growing css division

I am facing an issue where the tiles on my webpage expand on hover, but some of them are partially covered by neighboring tiles. How can I resolve this problem? Here is the CSS code snippet: .tile { position: absolute; width: 86px; background-color ...

Three.js: Obtain the latest vertex positions using morph targets

I have successfully implemented some morph targets in my project: View the working morph targets here (Don't forget to use the slider control to see the morph effect in action) However, I am facing an issue where I cannot access the updated position ...

Tips on preserving type safety after compiling TypeScript to JavaScript

TS code : function myFunction(value:number) { console.log(value); } JS code, post-compilation: function myFunction(value) { console.log(value); } Are there methods to uphold type safety even after the conversion from TypeScript to JavaScript? ...

Successfully transferring canvas image to server. Saving empty picture file

I have a piece of code that creates an image from an equation editor when the save button is clicked and displays it on a canvas. However, after displaying it, I am having trouble saving it as the saved image appears blank. Can someone please help me ident ...

guide on adding a variable to the link_to path

In my attempt to incorporate a variable into the link_to function below: <%= link_to '<button type = "button">Players</button>' .html_safe, live_players_path(:Team => @tmf) %> Whenever I click on this link, it seems to ...

angucomplete-alt: retrieving text value in case of no matches

Using Angucomplete-alt has been effective for me when I want to guide users into selecting from a pre-defined list of options. However, what if I want to allow users to enter free text and only provide suggestions as completions, rather than mandating a s ...

Is it possible to programmatically hide the Textarea and submit button for each row in a PHP-generated database table?

After spending a considerable amount of time on this project, I'm looking to incorporate a JavaScript effect (hide/unhide) into a basic submit form. Although the functionality is successful, it seems to be limited to only one row in the database tabl ...

A guide on implementing autocomplete functionality with ng-tags-input in AngularJs

I have a ng-tag field in my code as follows: <tags-input ng-model="services"></tags-input> My goal is to implement an autocomplete feature for this field without relying on jquery. The data required for the autocomplete functionality will co ...

Leveraging several useState hooks

When working on a React Native project, I have implemented multiple hooks to retrieve input data in a form. Are there any alternative methods that are more efficient or better suited for this task? Thank you const [name, setName] = useState(''); ...

The Vue.js route is not aligning with its defined path, causing a mismatch

Attempting to develop a Vue SPA app, but encountering an issue with the routes not matching what was defined in the router. Despite all configurations seemingly correct, there is confusion as to why this discrepancy exists. What element might be overlooked ...

Listen for the modified value in a directive with AngularJS

I am currently working on implementing a directive that can draw a chart based on specified values. What I am aiming for is to pass the data necessary for the plot directly from the template rather than using ng-model, as my current solution requires. I ...

Effortlessly update value changes in ReactJs when Checkbox is checked

I've been stuck on this issue for a whole day now. I'm trying to make it so when the checkbox is checked, the value of 'Done' changes as intended. I've tried using useState but it's not working. The approach I used below is mu ...

How to Pause or Temporarily Halt in Jquery?

Looking to lift the object up, wait 1000ms, and then hide it. I found this snippet of code: $("#test").animate({"top":"-=80px"},1500) .animate({"top":"-=0px"},1000) .animate({"opacity":"0"},500); However, using ".animate({"to ...

Tips for showcasing JavaScript variables on a webpage

I am working with various JavaScript variables that involve displaying values inside div elements. goalDiv = "<div class=goal-parent id=goal-parent"+Id+">"+ "<div class=goal>"+ "<div class=top-layer>"+ "<div class=compone ...

Switching between javascript objects within the redux store and the application

I am working with a set of JavaScript objects that are retrieved from an external API library. My goal is to save these objects in my React application using Redux. These objects are ES2015 classes that include two useful methods called fromJSON and toJSO ...

Restrict the character count in tinyMCE

My project uses the tinyMCe editor and everything is functioning properly. However, I now need to limit the number of characters that can be inserted into the tinyMce textarea. tinyMCE.init({ // General options mode : "textareas", theme : "simple", plugin ...

Parent window login portal

I have just started learning how to program web applications, so I am not familiar with all the technical terms yet. I want to create a login window that behaves like this: When a user clicks on the Login button, a window should pop up on the same page t ...

Learn the process of incorporating a plugin into a React JS project

As a ReactJs beginner, I am encountering an issue while trying to import a new plugin in my react app. I am currently working on React without using node or npm as shown below. <!-- some HTML --> <script src="https://unpkg.com/babel-standalone@6 ...