Ng-click not working second time with ng-hide interaction
I have two buttons and only one of them appears at the same time. The first is called "Offline mode", the other is "Online mode". They look like HTML:
<a ng-hide="offlineMode == true" ng-click="offlineMode()">Offline Mode</a>
<a ng-show="offlineMode == true" ng-click="onlineMode()">Online Mode</a>
When I click "Offline Mode" for the first time, it successfully goes to "Online Mode". When I click "Online Mode" after that it goes back to "Offline Mode". After that, the button becomes invisible. It is not included inside the function.
JS:
$scope.offlineMode = function() {
$scope.offlineMode = true;
// do other things
};
$scope.onlineMode = function() {
$scope.offlineMode = false;
// do other things
};
source to share
You are getting this error as function and flag variable have the same name offlineMode
See the console for this error:
v2.offlineMode is not a function
Fix:
Just rename the boolean variable to offline
(or whatever)
$scope.offlineMode = function() {
$scope.offline = true;
// do other things
};
$scope.onlineMode = function() {
$scope.offline = false;
// do other things
};
ANd update html accordingly
<a href="#" ng-hide="offline" ng-click="offlineMode()">Offline Mode</a><br>
<a href="#" ng-show="offline" ng-click="onlineMode()">Online Mode</a>
Note the changes in ng-hide
and ng-show
. You don't have to evaluate offline
with help every time true
.
Here's a demo
source to share
You don't need to create two buttons and two functions. You can do it in a simple way, for example:
<a ng-click="switchMode()">Switch Mode</a>
JS:
$scope.offlineMode = true;
$scope.switchMode = function() {
$scope.offlineMode = !$scope.offlineMode;
};
and if you want to change the button text you can do it like this:
<a ng-click="switchMode()">
<span ng-if="offlineMode">Online Mode</span>
<span ng-if="!offlineMode">Offline Mode</span>
</a>
source to share
I can't explain why it doesn't work, but consider using this approach:
<a ng-click="toggle()">{{caption}}</a>
$scope.online = true;
$scope.caption = 'Offline Mode';
$scope.toggle = function() {
$scope.online = !$scope.online;
$scope.caption = $scope.online ? 'Offline Mode' : 'Online Mode';
if ($scope.online) {
// do other things
} else {
// do other things
}
}
source to share