angularjs - How to inject service which depends on script running before it? -
in index.html have following code:
<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, variable not defined. console.log(json.stringify(response)); window.bootstrappeduserobject = response; } }); }); </script>
as services loaded have service follows:
(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; } }); })();
my service needs previous script run before run otherwise $window.bootstrappeduserobject undefined. how can structure calls script has returned before start building service(s)?
for case, can try using ng-if evaluate directive once $.ajax result has arrived
example :
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, variable not 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>
Comments
Post a Comment