Angular UI-Router: Difficulty in Child State Accessing Parent Controller

I am currently using ui.router's nested views feature in my Angular application. Here is the relevant part of my .config:

$urlRouterProvider.otherwise('/');

$stateProvider
.state('home', {
    url: '/',
    templateUrl: 'app/components/home/home.html',
    controller: 'HomeController'
})
.state('admin', {
    url: '/admin',
    templateUrl: 'app/components/admin/admin-dashboard.html',
    controller: 'AdminCtrl'
})
.state('admin.page-1', {
    templateUrl: 'app/components/admin/page-1/page-1.view.html',
    controller: 'AdminCtrl'
})

The Issue I'm facing is that even though the admin.page-1 view loads correctly within the admin view, it appears to lack access to the AdminCtrl.

This is the structure of the controller:

(function() {
    'use strict';

    angular
        .module('peaches')
        .controller('AdminCtrl', Controller);

    Controller.$inject = ['$scope'];

    function Controller($scope) {
        var vm = this;

        vm.test = "Hello."
        console.log(vm.test);

        vm.organization  = {
            name: "Western Fund"
        };

        activate();

        function activate() {

        }
    }
})();

While the console.log(vm.test) functions properly when navigating to admin.page-1, it does not seem to load inside my nested view, page-1.view.html, here:

<div class="col-xs-12">
    <h1>{{vm.test}}</h1>
</div>

What could be causing this issue?

Answer №1

Apédémak and dhavalcengg pointed out that I forgot to specify the controllerAs in my routes, which resulted in vm not being defined. Here is the solution that resolved the issue:

.state('admin', {
    url: '/admin',
    templateUrl: 'app/components/admin/admin.html',
    controller: 'AdminCtrl as vm'
})

Answer №2

It appears that the topic of discussion is sharing $scope between parent and child components utilizing ui-router. This post provides a detailed explanation along with an example:

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

Troubleshooting: Unable to create records in MongoDB using MEAN Stack

I am currently in the process of developing a MEAN stack application. My main objective at this point is to create a record in MongoDB from a form, but I seem to be encountering some issues. The data binding between the view and the controller appears to b ...

Do all Ajax requests automatically support the Spring Security CSRF Token Repository Cookies feature?

As I work my way through this security tutorial, I noticed that it sets up a CsrfTokenRepository in the following manner: .csrf().csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse()); Do you think this is all that's needed to enable Aj ...

Remove a comment from the page without needing to refresh the entire

Is there a way to enhance this code so that when a comment is deleted, the page does not refresh? It can be frustrating when deleting a comment causes the page to scroll back to the top. AJAX function deleteComment(pid){ $.ajax({ type: "PO ...

Guide to making a reusable AJAX function in JavaScript

Currently, I'm working on developing a function that utilizes AJAX to call data from another server and then processes the returned data using a callback. My goal is to be able to make multiple calls to different URLs and use the distinct responses in ...

The background color of the active tab is updated upon loading the page

I have attempted to modify this code to change the background color of li tag on click. It successfully changes the background color when hovering or clicking, but unfortunately reverts back to the default color upon page refresh. I am looking for a soluti ...

An array is not just a mere collection of elements

I have an object that resembles an array var items = [ { started_time: 2017-05-04T12:46:39.439Z, word: 'bottle', questionId: '161013bd-00cc-4ad1-8f98-1a8384e202c8' }, { started_time: 2017-05-04T12:47:26.130Z, word: &apo ...

AJAX: Building a Robust Single Page Application with Enhanced Security

Currently, I am developing a web/mobile application using AJAX. This app consists of 4 pages: the login page and three protected pages that are only accessible to logged-in users. My plan is to implement the Single Page Application pattern, where all 4 pa ...

Image flipping effect malfunctioning in Safari and Internet Explorer

My image flipping effect is not functioning properly in Safari and IE browsers. Here is the code I am using: .flipcard { position: relative; width: 220px; height: 220px; perspective: 500px; margin: auto; text-align: center; } .flipcard.v:hove ...

Error: React Beautiful D&D is unable to retrieve dimensions when no reference is specified

Hey everyone! I'm currently working on a meta form creator and having some trouble with performance issues. I created a sandbox to ask for help, but keep getting the error message "Cannot get dimension when no ref is set" when trying to drag a second ...

When attempting to insert the "$binary" key into MongoDB using Node.js, an error occurs stating that the key must not begin with a "$" symbol

When utilizing the node driver to insert records into mongo, I encountered an issue with a certain field in my collection: { "$binary": "base64 encoded binary" }. If I directly input a key beginning with $, it triggers an error: Error: key $binary must no ...

The Battle of node.js Modules: Comparing socket.io and express.static

The server.js file I am currently running is set up as follows: module.exports = server; var express = require('express'); var fs = require('fs'); var server = express.createServer(); var port = 58000; server.listen(port); var ...

Utilize JavaScript to parse JSON response data, calculate the average of a specified field while keeping track of

The data returned from the API call is structured as follows: var array = {"scores":[ { userid: "1", mark: 4.3 }, { userid: "1", mark: 3.8 }, { userid: "2", mark: 4.6 }, { userid: "2&quo ...

What is the best way to position an image alongside text using Vue and Buefy?

I'm looking to add an image next to my text in Vue using Buefy. Take a look at the code I have so far, can someone offer some guidance? <template> <section class="hero is-link is-fullheight-with-navbar"> <div cla ...

A step-by-step guide on modifying the box-shadow color using jquery

I have developed some JavaScript code that adjusts the box-shadow of buttons to be a darker version of their background color. This allows users to dynamically change the button background colors. The current code successfully changes the box shadow based ...

Utilizing URL Parameters and Query Strings in React Router: A Comprehensive Guide

Can someone help me retrieve the foo parameter value from http://localhost:3000/params?foo=123? I keep encountering an error message: Error: Params(...): No render output was returned. This typically indicates a missing return statement or returning null ...

What could be causing the redirection to my php file in this particular contact form?

I have a contact form on my website that uses AJAX for submission. Everything seems to be working fine, but when the user clicks on the Submit button, they are redirected to the PHP file instead of staying on the page to see success or error messages. I wa ...

Sending objects as parameters to a class in JavaScript - an easy guide

Having trouble passing a parameter to the class for handling AJAX errors. The initial function is as follows: function GetLastChangePass(UserId) { var field = { id: UserId, } var fieldStringified = JSON.stringify(field) $.ajax({ ...

Merging HTML Array with jQuery

I am working with input fields of type text in the following code snippet: <input type="text" minlength="1" maxlength="1" class="myinputs" name="myinputs[]" > <input type="text" minlength="1" maxlength="1" class="myinputs" name="myinputs[]" > ...

CSS classes designed to mimic JavaScript object attribute-value pairs

I stumbled upon some interesting css class-value combinations within HTML tags. It seems like a specific JavaScript code is interpreting this, but it's something I haven't encountered before. I came across this on www.woothemes.com/flexslider/ (y ...

Customizing the appearance of a JavaScript countdown timer's output on an individual basis

I am currently working on customizing the appearance of a JavaScript date counter. My goal is to style the days, hours, minutes, and seconds individually. Ideally, I want each unit to be right-aligned within its own div, with specific left and top absolute ...