Mezoo
Mezoo

Reputation: 769

Value not updated in ng-switch

I'm using ng-switch to change ui-sref's value but it seems it doesn't work because value was not updated. Initial value is false, then it keeps it.

Html :

<div ng-switch on="result">
    <div ng-switch-when=false ui-sref="gotest" class="gotest-button"></div>
    <div ng-switch-when=true ui-sref="menu" class="gotest-button"></div>
</div>

AppCtrl :

$scope.result=angular.isDefined(window.localStorage['result']);

Can you explain to me what is wrong please ?

Thanks

Upvotes: 0

Views: 577

Answers (1)

Ozu
Ozu

Reputation: 36

$scope.result=angular.isDefined(window.localStorage['result']);

code in AppCtrl runs once, set result value to false and that's all. You don't have any watchers. You could:

  • add watchers manually

    function getResultValue() {
       return angular.isDefined(window.localStorage['result'])
    }
    
    $scope.$watch(getResultValue, function(newValue) {
     $scope.result = newValue;
    });
    
  • call function in your view:

    // controller code: $scope.getResultValue = getResultValue // as in previous example

    // view
    <div ng-switch on="getResultValue()">
        <div ng-switch-when=false ui-sref="gotest" class="gotest-button"></div>
        <div ng-switch-when=true ui-sref="menu" class="gotest-button"></div>
    </div>
    

Services integrated with digest cycle will do the job too.
You could read about watchers here: https://docs.angularjs.org/api/ng/type/$rootScope.Scope

Update
I make some misleading assumptions. To react on changes you need to integrate them in angular digest cycle. My examples would work only if something will start digest. ngClick directive, $interval service or something else.
Example with interval here: http://jsfiddle.net/joshdmiller/hb7lu/

I dont really understand why newValue is added in watch function and not use in controller code, please could you explain

Code in controller wll run once. Code in watcher will run every digest. (angular expressions will be evaluated in your view after that)

For example:
0. Initial state: localStorage['result'] is undefined
1. app starts, digest is called, first ng-swith branch
2. Something changes localStorage['result'] value, now its defined
3. Digest called in reaction on something
4. All watchers is called
5. If some watcher changes $scope.result value, you get second ng-switch

Upvotes: 2

Related Questions