Angular 控制器和指令将值从控制器获取到指令中

Posted

技术标签:

【中文标题】Angular 控制器和指令将值从控制器获取到指令中【英文标题】:Angular controllers and directives getting values from controller into directive 【发布时间】:2017-06-05 23:01:29 【问题描述】:

我在我的 Angular 网站中有一个构建页眉的指令,在该页眉中我想显示用户的名字和姓氏。我将整个应用程序包装在 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\:formdisplay:block;.ng-animate-shimvisibility:hidden;.ng-anchorposition: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  src="http://placehold.it/40x40" >
            <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;
    );

]);

如何将我的用户对象从控制器中获取到指令中?

【问题讨论】:

【参考方案1】:

由于您使用的是MainController as main,请将 main 添加到您的指令中:

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

用户数据将通过您的“templates/partials/header.html”内的隔离范围两种方式绑定为user 对象提供,例如user.firstNameuser.lastName

您可以通过添加指令定义来避免使用$scope

controllerAs: 'ctrl';
bindToController: true;

您的用户数据将以ctrl.user 对象的形式在 HTML 中可用

【讨论】:

以上是关于Angular 控制器和指令将值从控制器获取到指令中的主要内容,如果未能解决你的问题,请参考以下文章

如何获取 Angular 输入指令数据以传递给控制器

将值从一个视图控制器传递到另一个视图控制器的问题

如何将值从表单传递到数据表

无法在指令 linkFn 中获取控制器引用

无法在指令linkFn中获取控制器引用

将值从视图传递到控制器,我错过了啥?