简体   繁体   English

AngularJS:在模板中访问注入的控制器

[英]AngularJS: Access injected controller in template

I have 2 controllers, ItemController and AuthenticationController . 我有2个控制器, ItemControllerAuthenticationController

AuthenticationController is injected into ItemController AuthenticationController被注入ItemController

ItemModule.controller('ItemController', function ($scope, AuthenticationController)

I am now trying to call the isLoggedIn() function in AuthenticationController from the template. 我现在尝试从模板中调用AuthenticationControllerisLoggedIn()函数。

How can I do that? 我怎样才能做到这一点?

One way is to put the IsLoggedIn method on the $scope , something like this: 一种方法是将IsLoggedIn方法放在$scope ,如下所示:

$scope.isLoggedIn = AuthenticationController.isLoggedIn

You can now call this function in your template 您现在可以在模板中调用此函数

<span>Logged In: <strong>{{IsLoggedIn()}}</strong></span>

I am not really sure whether injecting controllers is a good practice since each controller should focus on its own part. 我不确定注入控制器是否是一个好习惯,因为每个控制器应该专注于自己的部分。 If you want to share information among them, you should use services. 如果要在它们之间共享信息,则应使用服务。 Instead of injecting controllers; 而不是注入控制器; vou might nest them in your front end. 你可以把它们嵌在你的前端。 For example: 例如:

// js
app.controller('ParentController', function($scope) {
    $scope.person = {greeted: false};
});

app.controller('ChildController', function($scope) {
    $scope.sayHello = function() {
    $scope.person.name = "Ari Lerner";
    $scope.person.greeted = true;
    }
});

// html
<div ng-controller="ParentController">
    <div ng-controller="ChildController">
        <a ng-click="sayHello()">Say hello</a>
    </div>
    {{ person }}
</div>

// displayed:
{greeted:true, name: "Ari Lerner"}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM