3
我有一個工廠返回3個函數:setToken
,getToken
,isAuthenticated
。前兩個函數是預定義的,最後一個函數調用getToken
函數,使用this.getToken
。錯誤:this.getToken不是函數
將工廠注入控制器時,然後使用ng-show
調用第三個函數(isAuthenticated()
)。我的控制檯出現以下錯誤:
Error: this.getToken is not a function
[email protected]http://localhost:9000/scripts/services/authtoken.js:22:16
任何人都可以幫我解決我在做什麼錯嗎?
工廠:
'use strict';
angular.module('psJwtApp').factory('authToken', function($window) {
//define storage
var storage = $window.localStorage;
var cachedToken;
// Public API here
return {
setToken: function(token) {
cachedToken = token;
storage.setItem('userToken', token);
},
getToken: function() {
if (!cachedToken) {
cachedToken = storage.getItem('userToken');
}
return cachedToken;
},
isAuthenticated: function() {
//return true if we get something from getToken
return !!this.getToken();
}
};
});
控制器:
'use strict';
angular.module('psJwtApp').controller('HeaderCtrl', function($scope, authToken) {
$scope.isAuthenticated = authToken.isAuthenticated;
});
的觀點:
<ul class="nav navbar-nav">
<li ui-sref-active="active">
<a ui-sref="main">Home</a>
</li>
<li ng-hide="isAuthenticated()" ui-sref-active="active">
<a ui-sref="register">Register</a>
</li>
<li ng-show="isAuthenticated()" ui-sref-active="active">
<a ui-sref="logout">Logout</a>
</li>
</ul>
如果你覺得缺少任何東西或需要更多信息,請詢問我將其添加到問題中。
嘗試緩存此; var me = this; return !! me.getToken(); – Akis
仍然返回相同的錯誤 - 錯誤:me.getToken不是一個函數 –
你在哪裏聲明var me = this; ? – Akis