Showing or hiding elements based on variables in controller - Ionic

user818700 picture user818700 · Aug 13, 2015 · Viewed 18.7k times · Source

For all I know this might be more an AngularJS issue than an Ionic specific one. I have a button in one of my views:

<button class="button button-clear button-block button-positive" ui-sref="register">
    Register
 </button>

And in my controller I have this variable that I get from local storage that is either true or false and has to be hidden depending that the value is:

app.controller('loginController', ['$scope', '$localstorage',
  function($scope, $localstorage) {

  // Check if the user has already requested a register, and if true, hide
  // the 'Register' button
  if ($localstorage.get("registrationRequested", false) === true) {
    // How do I do this?
  }

}]);

Now the first question probably is, is it even a best practice to manipulate the dom like that from my controller? And if not, where and how do I do it? If its' fine doing it in my controller, then how do I reference that button and hide it?

Answer

Erazihel picture Erazihel · Aug 13, 2015

Add a ng-hide directive to your button tag:

<button ng-hide=registered class="button button-clear button-block button-positive" ui-sref="register">
    Register
</button>

In your JS file, declare this value in your $scope to false and set it to true to hide the button:

app.controller('loginController', ['$scope', '$localstorage',
    function($scope, $localstorage) {
        $scope.registered = false;

        // Check if the user has already requested a register, and if true, hide
        // the 'Register' button
        if ($localstorage.get("registrationRequested", false) === true) {
            $scope.registered = true;
        }
    }
]);