$rootScope undefined in an easy AngularJs Routing Demo

I've been trying to access the name and age using $scope and $rootScope, but I keep getting an error even though I'm pretty sure everything is set up correctly. Can someone please point out where I might be making a mistake?

<html>

<head> 

    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.5/angular.min.js"></script> 
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.5/angular-route.min.js"></script> 

</head> 

<body ng-app="myApp" ng-controller="myCtrl"> 

    <a href="#/one">One</a><a href="#/two">Two</a>

    <ng-view></ng-view>

    <script> 
    //app declaration
    var app = angular.module("myApp",['ngRoute']);

    //routing
    app.config(['$routeProvider',function($routeProvider){
        $routeProvider
        .when('/one',{templateUrl:'one.html'})
        .when('/two',{templateUrl:'two.html'})
        .otherwise({templateUrl:'one.html'});
    }]);

    //config 
    app.run(['rootScope', function($rootScope){
        $rootScope.age = 25;
    }]);

    //controller
    app.controller('myCtrl',function($scope, $rootScope){
        $scope.name = "Peter";
    });
    </script> 

</body> 

</html> 

one.html

ONE => {{name}},{{age}}

two.html

TWO => {{name}},{{age}}

Updated Error:

https://i.sstatic.net/4OCoC.png

Answer №1

Check out the documentation to see that the first parameter should be a function.

run(function(injectables) { // instance-injector
  // This is an example of a run block.
  // You can have as many of these as you want.
  // You can only inject instances (not Providers)
  // into run blocks
});

However, in your code

app.run('rootScope',function($rootScope,$state){

The first parameter is a string instead of a function.

Therefore, you should remove it, or if you want to use the injectable syntax, wrap it in an array like this:

app.run(['$rootScope','$state',function($rootScope,$state){...}]}

It appears that you have another error: you are using the $state provider, which is not part of the ngRoute module but rather part of ui-router. Even when the run block is executed, the current route might not be defined.

Here is a working sample without any unnecessary elements:

//app declaration
var app = angular.module("myApp", ['ngRoute']);

//routing
app.config(['$routeProvider', function($routeProvider) {
  $routeProvider
    .when('/one', {
      template: '<div>one: {{name}} | {{age}}</div>'
    })
    .when('/two', {
      template: 'two: {{name}} | {{age}}'
    })
    .otherwise({
      redirectTo: '/one'
    });
}]);

//config 
app.run(function($rootScope) {
  $rootScope.age = 25;
});

//controller
app.controller('myCtrl', function($scope, $rootScope) {
  $scope.name = "Peter";
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.5/angular.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.5/angular-route.js"></script>

<div ng-app="myApp" ng-controller="myCtrl">
  <ng-view></ng-view>
</div>

Answer №2

Make sure to include ngRoute as a dependency in your module

var myApp = angular.module("myApp", [ngRoute]);

Answer №3

The angular().run() code snippet shows how $rootScope and $state are injected.

app.run('rootScope',function($rootScope,$state){
    if($state.current.name == 'one'){$rootScope.age = 25;}
    if($state.current.name == 'two'){$rootScope.age = 30;}
});

It's important to note that $state cannot be injected since it is not part of the ngRoute module.

Answer №4

Spelling mistake found,

 app.run(['rootScope', function($rootScope){
    $rootScope.age = 25;
}]);

corrected version should read as

 app.run(['$rootScope', function($rootScope){
    $rootScope.age = 25;
}]);

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

jQuery ajax issue: Unable to locate file using relative path

I have recently transferred some script from an HTML document to an external file. I updated the jQuery path to point to the new location of the JavaScript file, but now it is unable to locate the necessary PHP file. Can anyone shed light on why this might ...

Unable to capture user input text using $watch in AngularJS when applied on ng-if condition

I have developed a cross-platform application using AngularJS, Monaca, and OnsenUI. In my login view, I check if the user has previously logged in by querying a SQLite database. Depending on whether there is data in the database, I either display a welcom ...

Having trouble launching the freshly developed Angular app

I'm encountering an issue with my newly created app - I can't seem to launch it. Error: The loader “C:/C#/Angular/my-app/src/app/app.component.css” is not providing a string as expected. https://i.sstatic.net/6Xjwd.png https://i.sstatic.ne ...

Generating a new array based on the keys found in a collection of objects

My array structure is quite complex with multiple objects containing different properties. let arr = [ { id: 1, name: "tony", hatColor: "blue" }, { id: 2, name: "larry", hatColor: "red" }, { id: 3, name ...

Tips to prevent the @click event from firing on a specific child component

When I click on any v-card, it redirects me to a different link. However, if I click on the title "World of the Day", I don't want anything to happen. How can I prevent being redirected when clicking on the title? https://i.sstatic.net/BM1gf.png tem ...

Running SOAP services with Jasmine framework in Node.js: A step-by-step guide

I've been successfully using the jasmine-node framework for automating my API tests. I can easily run REST services and retrieve results using node-fetch or http modules. However, my project also requires testing SOAP services. Can anyone provide guid ...

Encountering challenges with implementing debouncing functionality in React programming

import React,{useState} from 'react'; const app = () => { const [inputValue, setInputValue] = useState(); const handleChange = (e) => { setInputValue(e.target.value); console.log(inputValue); } const d ...

AngularJs Application Encountering Issues with Loading/Installing Google Maps API

I'm attempting to integrate Google Maps into my Angularjs app following the instructions provided here: http://angular-ui.github.io/angular-google-maps/#!/use After meticulously following all the steps, I encountered the following error: https://i.s ...

Oops! We encountered an internal issue: MongooseError: The operation `posts.insertOne()` has exceeded the buffering time limit of 100

Encountering an error when trying to post data to the Posts model upon clicking the post button: Internal error: MongooseError: Operation posts.insertOne() buffering timed out after 10000ms My setup includes a local MongoDB and Next.js 14 with app router. ...

transmitting a CSV file from PHP to the web browser

I have researched extensively on this topic, but I am still unable to make it work. My goal is to click a link in HTML and have it retrieve a text file (specifically a CSV). <button type="button" id="csvButton" class="genericButton"><a i ...

Angular - service workers leading to unsuccessful uploads

When uploading files using Uppy (XHRUpload) in my Angular 6 app, the process is smooth on localhost with the service worker disabled. However, enabling the service worker results in successful uploads only for small files, while larger files fail to upload ...

Reload the Angular application and navigate to a different state

Introduction In my extensive angular application, there are numerous forms for various items. These forms are associated with action objects that have unique schemaforms. The dropdowns in these forms vary based on the specific action and its parent comp ...

Node.js express version 4.13.3 is experiencing an issue where the serveStatic method is not properly serving mp3 or

I am currently utilizing Express 4.13.3 along with the serve-static npm module to serve static assets successfully, except for files with mp3 or ogg extensions. Despite reviewing the documentation, I have not come across any information indicating that thi ...

Easily transform your Twitter Bootstrap menu dropdown to appear on hover instead of click with this simple solution

Is there a way to make the toggle dropdown button display the dropdown menu when hovering over it instead of clicking? I tried using the Bootstrap method $().dropdown('show'). What are your thoughts on this approach? $(document).on("mouseenter ...

What is the best way to trigger the opening of a Component upon an onPress event?

One challenge I am facing is implementing a button in my app's Screen that should open a self-made Modal component on the same screen. To achieve this, I have set up a visible state in the screen and created an onPress handler for the button to toggl ...

Is there a way to add a sub-heading into the side menu?

We are currently developing an application that utilizes ngCordova and we want to implement a side menu feature. The side menu has already been set up and you can see it below. https://i.stack.imgur.com/fiv39.png After adding the subheader, this is how t ...

What is the best way to handle newline characters ( ) when retrieving text files using AJAX?

When using an AJAX call to read a text file, I encountered an issue where it reads the \n\t and backslash symbols. These characters are not needed in the pure text message. How can I ignore or remove them for a clean text display? ...

Sending JSON data from AngularJS to Laravel Controller through POST request

I have encountered an issue while using AngularJS to send POST data to a Laravel controller for saving into a database. The problem lies in the incorrect parsing of data from AngularJS to Laravel. The data being passed looks like this: $scope.invoice_ite ...

exploring the ins and outs of creating computed properties in TypeScript

How can I store an object with a dynamically assigned property name in an array, but unsure of how to define the array properly? class Driver { public id: string; public name: string; constructor(id , name) { this.id = id; th ...

Accessing the camera or photo library in React Native does not require any permissions

In my current project, I am developing an app that requires users to upload images from their photo library or camera. To access the camera functionality, I am utilizing the react-native-image-picker library without integrating react-native-permissions. ...