在我的index.html中,我有以下代码:
<script>
$(document).ready(function () {
var sessionId = document.URL.substr(document.URL.lastIndexOf('/') + 1);
$.ajax({
url: 'login/' + sessionId + '?format=json',
success: function (response) {
// if not logged in, then variable is not even defined.
console.log(JSON.stringify(response));
window.bootstrappedUserObject = response;
}
});
});
</script>
当我的服务被加载时,我有如下服务:
(function() {
"use strict";
var app = angular.module('helloApp.controllers');
app.factory('identity', function($window) {
var currentUser;
if (!!$window.bootstrappedUserObject) {
currentUser = $window.bootstrappedUserObject;
}
return {
currentUser: currentUser,
isAuthenticated: isAuthenticated,
isAdministrator: isAdministrator,
sessionId : sessionId
};
function sessionId() {
return currentUser.sessionId;
}
function isAdministrator() {
return this.currentUser.IsAdmin;
}
function isAuthenticated() {
return !!this.currentUser;
}
});
})();
我的服务需要在运行之前运行上一个脚本,否则$ window.bootstrappedUserObject将始终未定义。在开始构建服务之前,如何构建调用以便脚本返回?
答案 0 :(得分:1)
对于您的情况,您也可以尝试使用ng-if仅在$ .ajax结果到达时才评估指令
示例:
HTML
<div id="overlay" ng-show="!identity.isAuthenticated()" ng-if="Evaluate"><h1 class="centred" style="color:red">Not authenticated</h1></div>
<script>
$(document).ready(function () {
var sessionId = document.URL.substr(document.URL.lastIndexOf('/') + 1);
$.ajax({
url: 'login/' + sessionId + '?format=json',
success: function (response) {
// if not logged in, then variable is not even defined.
console.log(JSON.stringify(response));
window.bootstrappedUserObject = response;
var appElement = document.querySelector('[ng-app=myApp]');
var $scope = angular.element(appElement).scope();
$scope.$apply(function() {
$scope.Evaluate = true;
});
}
});
});
</script>