0

У меня есть директива на моем угловом веб-сайте, которая строит заголовок страницы в заголовке этой страницы. Я хочу показать имя и фамилию пользователя. Я завершаю все свое приложение в MainController. Мой визуализации 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> 

Моя не директива HTML выглядит следующим образом,

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

И мой код контроллера, и директива код выглядит это,

app.directive('header', [function() { 
return { 
    restrict: 'A', //This menas that it will be used as an attribute and NOT as an element. I don't like creating custom HTML elements 
    replace: true, 
    scope: {user: '='}, // This is one of the cool things :). Will be explained in post. 
    templateUrl: "/templates/partials/header.html", 
    controller: ['$scope', '$filter', function ($scope, $filter) { 
     // Your behaviour goes 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; 
    }); 

}]);

Как я могу получить объект-пользователь от контроллера в директиве?

ответ

0

Поскольку вы используете MainController as main, добавьте главную к вашей директиве:

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

чем пользовательские данные будут доступны через изолированный объем два способа связывания в вашем «Шаблоны/частичными/header.html» как user объект, что-то вроде user.firstName и user.lastName.

Вы можете избежать использования $scope путем добавления к вашему определению директивы

controllerAs: 'ctrl'; 
bindToController: true; 

чем ваши пользовательские данные будут доступны witin HTML в качестве ctrl.user объекта