AngularJS if-statements not responding after scope variable update


#1

Hello everyone,

I have a little question. I’m updating a scope variable inside a view, but the if statements in my controller aren’t responding as desired. I inserted some relevant code in this topic. I already read some things about apply and watch, but I can’t figure it out. Thanks in advance!

Controller.js:

  $scope.currentPeriod = "monthly";
  
  // Weekly
  if ($scope.currentPeriod == "weekly") {
    // some code
    $scope.nextWeek = function () {
      // some code
    };
    $scope.previousWeek = function () {
      // some code
    }
  };

  // Monthly
  if ($scope.currentPeriod == "monthly") {
    // some code
    $scope.nextWeek = function () {
      // some code
    };
    $scope.previousWeek = function () {
      // some code
    }
  };

dashboard.html

<a ng-click="currentPeriod = 'weekly'" class="button button-block button-balanced" id="feedback-button">Weekly</a>
<a ng-click="currentPeriod = 'monthly'" class="button button-block button-balanced" id="feedback-button">Monthly</a>
<a ng-click="info()" class="button button-block button-balanced" id="feedback-button">Ever</a>
...
<div id="datepicker" ng-if="currentPeriod == 'weekly'">
 <img src="img/circle_left.png" id="dashboard-arrow" ng-click="previousWeek()">
 <h4 id="date">{{startWeek | date:'dd/MM/yy'}} - {{endWeek | date:'dd/MM/yy'}}</h4>
 <img src="img/circle_right.png" id="dashboard-arrow" ng-click="nextWeek()">
</div>

<div id="datepicker" ng-if="currentPeriod == 'monthly'">
 <img src="img/circle_left.png" id="dashboard-arrow" ng-click="previousMonth()">
 <h4 id="date">{{startMonth | date:'MMMM yyyy'}}</h4>
 <img src="img/circle_right.png" id="dashboard-arrow" ng-click="nextMonth()">
</div>

Screenshot of the page:


#2

Since you are working with the variables, you must remove from your html the $scope
And work it like this:

<a ng-click="changeCurrentPeriod()">

In your Controller

$scope.changeCurrentPeriod = function(){
    if($scope.currentPeriod == 'weekly'){
        $scope.currentPeriod = 'monthly';
        //some code
    }else if ($scope.currentPeriod == 'monthly'){
        $scope.currentPeriod = 'weekly';
        //some code
    }
}

#3

Oops! That $scope in HTML was just a little error in copying the code over to this forum.

The suggested fix of creating a function changeCurrentPeriod is not resolving the issue. The dashboard has a date scroller, so if you put all the code of $scope.currentPeriod in a function, the page doesn’t work anymore. The code inside currentPeriod needs to stay available because there are 2 functions inside of it (updated this in my original post).