Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Show/hide element AngularJS based on Controller boolean variable

I am trying to hide/show a portion of a form based on a Controller boolean variable. this is my html code:

<div id="sheetform-container" ng-controller="SheetController as SheetCtrl">
  <form action="#">
    <div class="sheetform-row" ng-show="canShow('Price')">
      <div class="sheetform-left-col fl-left"><label for="sheetform-price">Price</label></div>
      <div class="sheetform-midlle-col fl-left"><input type="text" class="sheetform-input" id="sheetform-price" name="price" value="$ 0.00" /></div>
      <div class="sheetform-right-col fl-right"></div>
    </div>
  </form>
</div>

I have created a function that changes the Price attribute to true/false according to the value sent, its called setConfig. This is how the Controller code looks like:

ngApp.controller('SheetController', ['$scope', function($scope) {
    $scope.Price = true;

    $scope.canShow = function(field) {
        return $scope.Price;
    }

    $scope.setConfig = function(config) {
        $scope.Price = config.Price;
    }
}]);

Any idea what am I missing?

Thanks!

like image 759
relez Avatar asked Aug 07 '14 16:08

relez


1 Answers

If you are intending for price to be the actual price of something then you shouldn't be using that for the boolean in this case. Assign the price using ng-model. Also, don't use a capital letter to name a variable. Only classes should be capitalized.

<div id="sheetform-container" ng-controller="SheetController as SheetCtrl">
  <form action="#">
    <div class="sheetform-row" ng-show="showPrice">
      <div class="sheetform-left-col fl-left"><label for="sheetform-price">Price</label></div>
      <div class="sheetform-midlle-col fl-left"><input type="text" class="sheetform-input" id="sheetform-price" name="price" ng-model="price" /></div>
      <div class="sheetform-right-col fl-right"></div>
    </div>
  </form>
</div>

Then in your controller you can remove the function you have and also initialize the variables

ngApp.controller('SheetController', ['$scope', function($scope) {
    $scope.showPrice = true;
    $scope.price = null;

}]);

I'm not sure how you are determining whether the price should be shown or not but you can either have $scope.showPrice assigned to a property in whatever object the form is for or if it's a toggle then you can just say:

<a href ng-click="showPrice = !showPrice"></a>
like image 133
Rorschach120 Avatar answered Sep 19 '22 19:09

Rorschach120