我有以下代码: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,谢谢你的回答。我试过这些解决方案,但不幸的是,它不起作用。 –