Retrieving data from controllers and passing it to directives in Angular applications

I have integrated a directive into my Angular website to generate a customized page header. Within this header, I aim to display the user's first and last name. My application is enclosed within a MainController. Below is the rendered HTML:

<html ng-app="app" ng-controller="MainController as main" class="fa-events-icons-failed ng-scope">
<head>
    <style type="text/css">@charset "UTF-8";[ng\:cloak],[ng-cloak],[data-ng-cloak],[x-ng-cloak],.ng-cloak,.x-ng-cloak,.ng-hide:not(.ng-hide-animate){display:none !important;}ng\:form{display:block;}.ng-animate-shim{visibility:hidden;}.ng-anchor{position:absolute;}</style>
    <meta charset="utf-8">
    <title ng-bind="main.windowTitle" class="ng-binding">App School Management</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
    <link rel="stylesheet" type="text/css" href="dist/css/generic.css">
    <link rel="stylesheet" type="text/css" href="dist/css/styles.min.css">
    <script src="https://use.fontawesome.com/2a6c262d81.js"></script><script src="https://cdn.fontawesome.com:443/js/stats.js"></script>
    <link rel="stylesheet" href="https://use.fontawesome.com/2a6c262d81.css" media="all">
</head>
<body cz-shortcut-listen="true">
    <div id="page-wrapper">
    <div id="page-header" class="bg-gradient-9 ng-isolate-scope" header="" user="userModel">
    <div id="mobile-navigation">
        <button id="nav-toggle" class="collapsed" data-toggle="collapse" data-target="#page-sidebar"><span></span></button>
        <a href="index.html" class="logo-content-small" title="MonarchUI"></a>
    </div>
    <div id="header-logo" class="logo-bg">
        <a ui-sref="dashboard.home" class="branding" title="Schoozle">
        App Logo
        </a>
        <a id="close-sidebar" href="#" title="Close sidebar">
        <i class="fa fa-chevron-left" aria-hidden="true"></i>
        </a>
    </div>
    <div id="header-nav-left">
        <div class="user-account-btn dropdown">
            <a href="#" title="My Account" class="user-profile clearfix" data-toggle="dropdown">
            <img width="28" src="http://placehold.it/40x40" alt="Profile image">
            <span ng-bind="$scope.user.first_name" class="ng-binding"></span>
            <i class="fa fa-chevron-down" aria-hidden="true"></i>
            </a>
        </div>
    </div>
    <!-- #header-nav-left -->
    <div id="header-nav-right">
        <div class="dropdown" id="notifications-btn">
            <a data-toggle="dropdown" href="#" title="">
            <span class="small-badge bg-yellow"></span>
            <i class="fa fa-bell" aria-hidden="true"></i>
            </a>
            <div class="dropdown-menu box-md float-right">
                <!-- Notifications Dropdown -->
            </div>
        </div>
    </div>
</div>

Here is how the non-directive HTML structure looks like:

<div header user="userModel"></div>

Below are the snippets of my controller and directive code:

app.directive('header', [function () {
return {
    restrict: 'A',
    replace: true,
    scope: {user: '='},
    templateUrl: "/templates/partials/header.html",
    controller: ['$scope','$filter', function ($scope, $filter) {
        // Add functionality here
    }]
}

}]);

app.controller('MainController', ['$scope', 'UserService', function($scope, UserService){
var self = this;

this.windowTitle = "App School Management";
this.loading = true;
this.user = {};

UserService.authenticatedUser()
    .then(function(response){
        self.loading = false;
        self.userModel = response.message;
    }, function(error) {
        self.hasError = true;
        self.errors = error.message;
    });

}]);

How can I pass the user object from the controller to the directive?

Answer №1

When utilizing MainController as main, make sure to include main in your directive:

<div header user="main.userModel"></div>

This will allow you to access user data through two-way binding within your isolated scope in 'templates/partials/header.html', such as user.firstName and user.lastName.

To avoid using $scope, add the following to your directive definition:

controllerAs: 'ctrl';
bindToController: true;

With this setup, your user data can be accessed in HTML using ctrl.user object.

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

Customize your AngularJS select element using Zurb Foundation's custom form features

I recently embarked on a project utilizing Zurb Foundation where I am tasked with developing dynamic select form fields using AngularJS. While the example showcased at http://jsbin.com/egizel/1/edit functions flawlessly, I encountered an issue when attemp ...

Remove the option to delete without making any changes to the flash file

Utilizing the DataTable javascript tool to export a grid, I have obtained the following HTML generated code: <div class="DTTT_container"> <a class="DTTT_button DTTT_button_copy" id="ToolTables_example_0" tabindex="0" aria-controls="e ...

The Vue application successfully compiles but fails to load in the web browser

Upon running npm run serve on my Vue app, the console displays the following output: DONE Compiled successfully in 17450ms 2:15:55 PM App running at: - Local: ...

Why is the body the last element in Angular modules arrays?

I have a question regarding architectural practices. When defining an Angular module, one common approach is to do it like this: angular.module('app', []) .controller('Ctrl', ['$scope', function Ctrl($scope) { //body.. ...

What is the most effective way to inform the user when the nodeJS server can be accessed through socketIO?

I have developed a web app that indicates to the user when the server is online for data submission. Although the current code functions properly for single-user interaction, I am facing an issue where one user's connection or disconnection directly i ...

Automated form with built-in calculations

Whenever a product is selected from the dropdown menu, the price value should be automatically filled in the input field with ID #price. Then, the user can enter the quantity in the input field with ID #quantity, and the total sum of price multiplied by qu ...

Unable to retrieve push token for the device. Please verify the validity of your FCM configuration

Looking for a solution to the issue of obtaining a push token Error: Unable to retrieve push token for device. Ensure that your FCM configuration is correct I have integrated Expo permissions and notifications in my React Native app, but nothing seems to ...

Consistent sizing for Bootstrap thumbnail images

In my current project, I am implementing a Bootstrap thumbnail feature where each thumbnail consists of an image and a heading. However, a problem arose as the images do not have the same size, resulting in thumbnails with varying dimensions. To resolve th ...

The loading of angular.min.js.map fails in Ionic

While running my Ionic app in the iOS simulator and using the Safari Web inspector, I encountered the following error: file:///.../.../Application/.../myApp.app/www/lib/ionic/js/angular.min.js.map Failed to load resource: The requested URL was not found o ...

Unable to update the Angular scope variable directly inside an AJAX call

var request = { "RequestId": $scope.$parent.req_id, "RequestDate": new Date(), "RequestDetails": $scope.$parent.details }; $scope.request_status = "pending"; $.ajax({ type: "POST", url: ...

Send two values from a select box when it is chosen

I am currently facing a challenge where I need to retrieve two related values when a select box is changed. The select box is set up to allow multiple selections and contains options that represent user resources, some of which are parent resources. My goa ...

Dynamic Route Matching in NextJS Middleware

Currently, I am in the process of developing a website that incorporates subdomains. Each subdomain is linked to a file-based page using middleware. Take a look at how the subdomains are being mapped to specific pages: app.com corresponds to /home app.com ...

Retrieve the result of the asynchronous operation represented by the $q promise

//controller for connecting to API .controller('LoginConnect', ['$scope', 'connecting', function($scope,connecting){ $scope.user = {}; var users = $scope.user; $scope.connect = function (users) { var log = ...

Fill an HTML div with JSON data obtained from a server

I am trying to display JSON data from a json-rpc server inside an HTML div. I can see the data in Chrome and Firefox dev tools, but I need it to be displayed within a specific div on the page. I have written a script to populate the 'mybox' div, ...

The setInterval example provided in the Javascript Mozilla documentation does not seem to be functioning properly on JSFiddle

I referred to Example #2 in the Mozilla docs about setInterval() (https://developer.mozilla.org/en-US/docs/Web/API/window.setInterval?redirectlocale=en-US&redirectslug=DOM%2Fwindow.setInterval#Example_1.3A_Generic) in my JSFiddle but the text color doe ...

AngularJS HTTP POST request encounters 405 Method Not Allowed error on IIS 8.5 platform

I keep receiving a "405 Method Not Allowed" error with my AngularJS application on PHP running on IIS 8.5. Here are the headers in my request... Access-Control-Allow-Headers:Content-Type, Accept Access-Control-Allow-Methods:GET, POST, PUT, DELETE, OPTION ...

Tips for integrating jquery functions with angularJS?

I'm having issues with my accordion menu implemented using jQuery in my AngularJS application. Currently, it's not functioning as expected. I have made some changes in the CSS by commenting out the display: none; for .menu-navigation ul ul to dem ...

``There seems to be a problem with the module execution

Currently, I am working on an AngularJS application where I need to ensure that the app only boots up once all data is fully loaded. To achieve this, I am trying to make requests in JSONP format and loading the $resource module using a .run statement. Bel ...

Retrieving modified object values in Node.js - A comprehensive guide

How can I retrieve the modified value of an object? The file index.js is executed before index2.js and here's what my code looks like: var object = { size:'5' }; var setSize = function(size) { object.size = size; } exports.object ...

Combining Jquery with Append to Dynamically Update PHP Variables

Code Snippet (index.html) <script> $(document).ready(function() { var interval = setInterval(function() { $.get("load_txt.php", { 'var1': 4, 'var2' : 52}, function(data){ $('#msg' ...