我有以下代碼: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(),但它說$摘要已經在進行中。
,如果你面對正在進行$消化,可以使用$超時錯誤,因爲在超時結束時調用$ apply。請參閱:http://stackoverflow.com/questions/12729122/angularjs-prevent-error-digest-already-in-progress-when-calling-scope-apply然而,主要問題似乎是別的 –
聽起來像你有一些你的頁面上的其他錯誤,因爲你在ng-class中的代碼看起來是正確的。如果您只是在網頁某處輸出{{userLanguage}},它是否按預期更新? – jtsnr
@KiranYallabandi,謝謝你的回答。我試過這些解決方案,但不幸的是,它不起作用。 –