2016-11-21 66 views
0

我有以下代码:AngularJS:ngClass不是HTTP请求后更新

angular.module('myApp') 
 
    .controller('MyCtrl', function ($scope,$rootScope, $filter, $location,$translate,$cookies,NavigationService) { 
 
    
 
\t   $scope.appVersion = ""; 
 
\t   $scope.credentials = {}; 
 
\t   $scope.userLanguage = null; 
 
\t   
 
\t   var init = function(){ 
 
\t   \t authenticate(); 
 
\t   \t getAppVersion(); 
 
\t   }; 
 
\t   
 
\t   var getAppVersion = function() { 
 
\t   \t NavigationService.getAppInfo() 
 
\t     .then(function (response) { 
 
\t      $scope.appVersion = response.data.build.version 
 
\t     }); 
 
\t   }; 
 
\t   
 
\t   var authenticate = function (credentials, callback) { 
 
\t    $rootScope.authorities = []; 
 
\t    $rootScope.currentUser = null; 
 

 
\t    NavigationService.doAuthentication(credentials).success(function (data) { 
 
\t     $rootScope.authenticated = !!data.name; 
 
\t     $rootScope.authorities = data.authorities; 
 
\t     $rootScope.currentUser = data.name; 
 
\t     $scope.userLanguage = data.userLang; 
 
\t     callback && callback(); 
 
\t    }).error(function (response) { 
 
\t     $rootScope.authenticated = false; 
 
\t     callback && callback(); 
 
\t    }); 
 
\t   }; 
 
...
<div ng-show="authenticated" class="btn-group btn-group-xs btn_change_language"> 
 
     <button ng-class="{'button_selected': userLanguage == 'de'}" class="btn btn-default" 
 
       ng-click="changeLanguage('de')" translate> 
 
      BTN_GERMAN_LANGUAGE 
 
     </button> 
 
        
 
     <button ng-class="{'button_selected': userLanguage == 'en'}" 
 
       class="btn btn-default" ng-click="changeLanguage('en')" translate> 
 
      BTN_ENGLISH_LANGUAGE 
 
     </button> 
 
</div>

的问题是,当我打开浏览器并加载网页时,ngClass指令得到userLanguage的初始值(空),而不是来自我的请求(data.userLang)的值,所以类“buttom_selected”不适用。我已经调试过了,值正常,但是如果我重新加载页面,ngClass只是更新。奇怪的是,如果我打开一个新的选项卡,它可以正常工作,但是如果我关闭并打开浏览器并访问应用程序,那么ngClass将忽略NavigationService回调所做的更改。

我尝试了$ scope。$ apply(),但它说$摘要已经在进行中。

+0

,如果你面对正在进行$消化,可以使用$超时错误,因为在超时结束时调用$ apply。请参阅:http://stackoverflow.com/questions/12729122/angularjs-prevent-error-digest-already-in-progress-when-calling-scope-apply然而,主要问题似乎是别的 –

+0

听起来像你有一些你的页面上的其他错误,因为你在ng-class中的代码看起来是正确的。如果您只是在网页某处输出{{userLanguage}},它是否按预期更新? – jtsnr

+0

@KiranYallabandi,谢谢你的回答。我试过这些解决方案,但不幸的是,它不起作用。 –

回答

0

我不确定通过尝试使用对象而不是字符串。

$scope.userLanguage = {title: null}; 

如果不工作,然后做一个小例子,像这样的,并尝试了解什么是错的:

<button 
     ng-class="{'active': userLanguage == 'de'}" 
     ng-click="userLanguage = 'de'">BTN_GERMAN_LANGUAGE</button> 
    <button 
     ng-class="{'active': userLanguage == 'en'}" 
     ng-click="userLanguage = 'en'">BTN_ENGLISH_LANGUAGE</button> 

Example

+0

Hi @Gennady,谢谢你的回答,但不幸的是它不起作用。 –

+0

我已经更新了我的答案 –

+0

Hi @Gennady,再次感谢。我看到你的例子,但是我的情况有点不同。当我碰到按钮时它工作正常,问题是当我用$ http调用加载页面时。当我第一次加载应用程序时,我的变量没有使用回调函数中的值进行更新。 –