[英]Can't access to injected AngularJS services within a function in a controller
[英]AngularJS: Access injected controller in template
我有2個控制器, ItemController
和AuthenticationController
。
AuthenticationController
被注入ItemController
ItemModule.controller('ItemController', function ($scope, AuthenticationController)
我現在嘗試從模板中調用AuthenticationController
的isLoggedIn()
函數。
我怎樣才能做到這一點?
一種方法是將IsLoggedIn
方法放在$scope
,如下所示:
$scope.isLoggedIn = AuthenticationController.isLoggedIn
您現在可以在模板中調用此函數
<span>Logged In: <strong>{{IsLoggedIn()}}</strong></span>
我不確定注入控制器是否是一個好習慣,因為每個控制器應該專注於自己的部分。 如果要在它們之間共享信息,則應使用服務。 而不是注入控制器; 你可以把它們嵌在你的前端。 例如:
// 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.