A guide on implementing nested view objects in ui-router for angular applications

Unfortunately, I am not well-versed in Angular. My objective is to display multiple views on a user profile page using ui-router. These are my current routes:

(function() {
'use strict';

angular
    .module('app.routes')
    .config(routesConfig);

routesConfig.$inject = ['$stateProvider', '$locationProvider', '$urlRouterProvider', 'RouteHelpersProvider'];
function routesConfig($stateProvider, $locationProvider, $urlRouterProvider, helper){

    // Enable HTML5 Mode
    $locationProvider.html5Mode(false);

    // Defaults to dashboard
    $urlRouterProvider.otherwise('/app/home');

    // Application Routes
    $stateProvider
      .state('app', {
          url: '/app',
          abstract: true,
          templateUrl: helper.basepath('app.html'),
          resolve: helper.resolveFor('fastclick', 'modernizr', 'icons', 'screenfull', 'animo', 'sparklines', 'slimscroll', 'classyloader', 'toaster', 'whirl','loaders.css', 'spinkit','jquery-ui', 'jquery-ui-widgets','weather-icons', 'skycons')
      })
      .state('app.home', {
          url: '/home',
          title: 'Home',
          templateUrl: helper.basepath('home.html'),
      })
      .state('app.user', {
          url: '/user',
          title: 'User',
          templateUrl: helper.basepath('user.html'),
          resolve: helper.resolveFor('datatables')
      })
      .state('app.user.dashboard', {
          url: '',
          views: {
            'eventTable': {
              templateUrl: helper.basepath('eventTable.html'),
            },
            'bankStatement': {
              templateUrl: helper.basepath('bankStatement.html'),
            }
          }
      })
} // routesConfig

})();
  • app provides the general structure.
  • app.home is the landing page with all users.
  • app.user should display a user's profile page with two tables (eventTable, bankStatement) rendered through two views.

I am unsure if the app.user.dashboard state is necessary, but I am unsure how to render the views inside the app.user state. Here is the rest of the pertinent code:

user.html

<h3>User Profile</h3>
<div ui-view="eventTable"></div>
<div ui-view="bankStatement"></div>

bankStatement.html

<div class="panel panel-default">
   <div id="bankStatementHeader" class="panel-heading">Events</div>
   <div class="panel-body">
      <div ng-controller="EventTableController as table2">
         <table datatable="ng" class="row-border hover">
            <thead>
               <tr>
                  <th>Date</th>
                  <th>Type</th>
                  <th>Description</th>
               </tr>
            </thead>
            <tbody>
               <tr ng-repeat="event in table2.events">
                  <td>{{ event.date }}</td>
                  <td>{{ event.type }}</td>
                  <td>{{ event.description }}</td>
               </tr>
            </tbody>
         </table>
      </div>
   </div>
</div>

eventTable.html

<div class="panel panel-default">
   <div id="bankStatementHeader" class="panel-heading">Bank Statement</div>
   <div class="panel-body">
      <div ng-controller="BankStatementController as table1">
         <table datatable="ng" class="row-border hover">
            <thead>
               <tr>
                  <th>Person ID</th>
                  <th>Event Date</th>
                  <th>Process Date</th>
                  <th>Details</th>
                  <th>Description</th>
                  <th>Amount</th>
                  <th>Balance</th>
               </tr>
            </thead>
            <tbody>
               <tr ng-repeat="statement in table1.statements">
                  <td>{{ statement.id }}</td>
                  <td>{{ statement.eventDate }}</td>
                  <td>{{ statement.processDate }}</td>
                  <td>{{ statement.details }}</td>
                  <td>{{ statement.description }}</td>
                  <td>{{ statement.amount }}</td>
                  <td>{{ statement.balance }}</td>
               </tr>
            </tbody>
         </table>
      </div>
   </div>
</div>

eventTable controller

function() {
    'use strict';

    angular
        .module('app.eventTable')
        .controller('EventTableController', EventTableController);

    EventTableController.$inject = ['$resource', 'DTOptionsBuilder', 'DTColumnDefBuilder'];
    function EventTableController($resource, DTOptionsBuilder, DTColumnDefBuilder) {
        var vm = this;

        activate();

        function activate() {

          // Ajax

          $resource('server/event-table.json').query().$promise.then(function(events) {
             vm.events = events;
          });
        }
    }
})();

bankStatements controller

(function() {
    'use strict';

    angular
        .module('app.bankStatement')
        .controller('BankStatementController', BankStatementController);

    BankStatementController.$inject = ['$resource', 'DTOptionsBuilder', 'DTColumnDefBuilder'];
    function BankStatementController($resource, DTOptionsBuilder, DTColumnDefBuilder) {
        var vm = this;
        activate();

        function activate() {

          // Ajax

          $resource('server/bank-statement.json').query().$promise.then(function(statements) {
             vm.statements = statements;

          });
        }
    }
})();

Any assistance would be highly appreciated. Thank you!

Answer №1

It is important to keep the app.user state abstract for better organization. Directly accessing the app.user state can lead to confusion, especially when dealing with child templates (ui-views).

To address this, I have updated the routes configuration to transform app.user into an abstract state. Additionally, the URL /user is now linked to the app.user.dashboard state.

While I have not conducted tests, I believe that this code should function correctly.

(function() {
'use strict';

angular
    .module('app.routes')
    .config(routesConfig);

routesConfig.$inject = ['$stateProvider', '$locationProvider','$urlRouterProvider', 'RouteHelpersProvider'];
function routesConfig($stateProvider, $locationProvider, $urlRouterProvider, helper){

    // Enable HTML5 Mode if needed
    $locationProvider.html5Mode(false);

    // Set default route to dashboard
    $urlRouterProvider.otherwise('/app/home');

    // Application Routes
    $stateProvider
      .state('app', {
          url: '/app',
          abstract: true,
          templateUrl: helper.basepath('app.html'),
          resolve: helper.resolveFor('fastclick', 'modernizr', 'icons', 'screenfull', 'animo', 'sparklines', 'slimscroll', 'classyloader', 'toaster', 'whirl','loaders.css', 'spinkit','jquery-ui', 'jquery-ui-widgets','weather-icons', 'skycons')
      })
      .state('app.home', {
          url: '/home',
          title: 'Home',
          templateUrl: helper.basepath('home.html'),
      })
      .state('app.user', {
          abstract: true,
          templateUrl: helper.basepath('user.html'),
          resolve: helper.resolveFor('datatables')
      })
      .state('app.user.dashboard', {
          url: '/user',
          title: 'User',
          views: {
            'eventTable': {
              templateUrl: helper.basepath('eventTable.html'),
            },
            'bankStatement': {
              templateUrl: helper.basepath('bankStatement.html'),
            }
          }
      })
    } // routesConfig

})();

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

Image malfunction in jquery blockui occurs following multiple AJAX requests, except when within the success function of an AJAX request

I have a perplexing question that has been on my mind. While I am aware of the issue and its resolution, I am struggling to comprehend the underlying reason. There is a particular method that goes through some preliminary steps, validation, saving, and cl ...

Is there a way to utilize jQuery for parsing the XML file?

When trying to parse the file, the value for "name" in the code is always an empty string. Here is my XML data: <row> <id>1</id> <AnrufenZahl>64</AnrufenZahl> <NameOperator>Ioan</NameOperator> </row> ...

How can you prevent JQuery AJAX from automatically redirecting after a successful form submission?

Encountered an issue with loading http://example.com/signup.ashx: The redirect from 'http://example.com/signup.ashx' to '' was blocked by the CORS policy. This is due to the absence of 'Access-Control-Allow-Origin' header on t ...

Guidelines for sending an array from a Laravel Controller through AJAX and generating a button based on the received data

Before making a selection, I click on the Color button: <form class="form form-variant"> {{ csrf_field() }} <button type="submit" class="btn btn-success che ...

App:// is where Electron and Vue API requests converge

Recently, I successfully integrated Electron into my Vue app with the help of the Vue CLI Plugin Electron Builder. During development, all API requests were properly directed to the address specified in my vue.config.js: proxy: { '^/api': ...

Creating a search bar with React-Redux: A step-by-step guide

Hey everyone, I've got this component here: const Iphone = ({phones,searchQuery}) => { const filterIphone = phones.map((p, index) => (<div className="model" key={index}> <NavLink to={'/p/' + p.id}>{p.body.mod ...

Creating a timer implementation in Node.js using Socket.IO

In the process of developing a drawing and guessing game using node.js and socket.io, I have a structure consisting of a Room class, a Game class (which is an extension of Room), and a Round class where each game consists of 10 rounds. During each round, a ...

A loop variable in Javascript is a function that iterates

var x = 99; while (true) { function lyrics(person) { return x + " " + "lines of code in the file " + x + " " + person + (x-1) + " lines of code" + "!"; } console.log(lyrics("John strikes one out, clears it all out ;")); x -= 1; if (x ...

Vue caution: The reference to property or method "list" during render is not defined on the instance. Ensure that this property is reactive and properly declared

I'm currently exploring the characters from the Rick & Morty series app using vue.js, and I am still learning how to use vue.js. However, I encountered the following error and would appreciate help in resolving it: Error1: [Vue warn]: Property or me ...

"The issue of a malfunctioning selected option in a select dropdown within an AngularJS application

I've been experiencing some odd behavior with my Dropdown control in an AngularJS application. The selected="selected" attribute doesn't seem to be working, resulting in blank default selected values. Additionally, I'm having trouble with t ...

Meteor is failing to update the data in MongoDB

I have encountered an issue with the following code snippet: Nodes = new Meteor.Collection("nodes"); [...] Template.list.events({ 'click .toggle': function () { Session.set("selected_machine", this._id); Nodes.update(Session.get("s ...

Importing JSON Data into an HTML File

I need to load a JSON file containing HTML content into my main HTML file upon clicking a button. ABC.json includes: <li><img src="images/picture6.jpg" /></li> <li><img src="images/picture5.jpg" /></li> <li><i ...

ng-grid displaying incorrectly in Internet Explorer 8

My ng-grid view is not displaying correctly in IE when in IE8 Standards Document Mode. It seems that the CSS styles generated dynamically by Angular are not being rendered properly. Although the solution mentioned here does not help, as I am using a newer ...

What strategies can be used to evaluate the performance benchmarks of AngularJS components?

One of my mandatory tasks involves analyzing the performance benchmarks for various AngularJS components like ng-grid and data-tables in IE8, Chrome, and FF using mock data. I have already set up the mock data. While utilizing the IE8 Profiler, I am obtai ...

AngularJS combined with jVectorMap allows for the seamless rendering of small interactive

I am facing a similar issue to one discussed here, but with some minor differences. Initially, my map loaded without any problem on the site. However, after adding Angularjs to the site, I noticed a 'small' map issue. It seems like a simple code ...

Angular JS Troubleshooting: Application Not Functioning Properly

I've been learning AngularJS on codeSchool and I ran into an issue with my simple hello world app. It was working fine at first but then stopped completely. I can't seem to find the bug, so any help would be appreciated. Here is the HTML code: & ...

Prevent typing in text box when drawer is activated by pressing a button

update 1 : After removing unnecessary files, I need assistance with https://codesandbox.io/s/0pk0z5prqn I am attempting to disable a textbox. When clicking the advanced sports search button, a drawer opens where I want to display a textbox. The toggleDra ...

What is the method with the greatest specificity for applying styles: CSS or JS?

When writing code like the example below: document.querySelector('input[type=text]').addEventListener('focus', function() { document.querySelector('#deletebutton').style.display = 'none' }) input[type=text]:focu ...

Ways to disperse items within another item

I have an inner object nested inside another object, and I am looking to extract the values from the inner object for easier access using its id. My Object Resolver [ { _id: { _id: '123456789', totaloutcome: 'DONE' }, count: 4 }, { ...

Invoking Node to utilize React/Webpack module code

Trying to figure out how to integrate client-side import/export modules into a Node.js require script within my custom NextJS webpack config: module.exports = { webpack: (config, options) => { if (options.isServer) { require("./some-scr ...