Jorge Sampayo
Jorge Sampayo

Reputation: 868

Access controller variables in methods dynamically

I have a controller in angular where there is a huge form split in cards. So each time a user picks a title, the card for that section shows (ex. name parts, address parts, contact data, college data, work data, etc).

The relevant code for doing that with only two sections is this:

angular.module('controllers', [])
.controller('EditUserController', function($scope, $state) {

  $scope.mustShowName = false;
  $scope.mustShowContact = false;

  $scope.toogleShowContact = function() {
    if ($scope.mustShowContact) {
      $scope.mustShowContact = false;
    } else {
      $scope.mustShowContact = true;
    }
  };
  $scope.toogleShowName = function() {
    if ($scope.mustShowName) {
      $scope.mustShowName = false;
    } else {
      $scope.mustShowName = true;
    }
  };
});

But there are various cards. There is a way of refactoring that in something like this?:

$scope.toogleSection = function(section) {
  if (section) {
    section = false;
  } else {
    section = true;
  }
};

...

$scope.toogleSection($scope.mustShowName);

If I try it, it doesn't work and doesn't throw errors, so I think it is just copying the variable and not referencing the original one.

Upvotes: 1

Views: 45

Answers (3)

Jess Patton
Jess Patton

Reputation: 2486

You can use a ng-if="show" for the detailed part of the card. Then do a ng-click="show = !show". BAM! you have a toggle on touch that will show and hide whatever you put the ng-if on. Here is a example from a app I made.

<div class="item" ng-show="directions">
    <!--directions go here-->
</div>
    <div style="text-align: center; background-color:#284f9a;" class="item" ng-click="directions = !directions">
        <p style="color: white;" ng-if="directions == false">See Directions:</p>
        <p style="color: white;" ng-if="directions == true">Close Directions:</p>
</div>

with this I can show and hide the directions and change what the show/hide button says. This also works really well with ng-repeat and only toggles the item you click on.

Upvotes: 1

Ori Drori
Ori Drori

Reputation: 191976

When you ask for $scope.mustShowName you just get the value and not the reference of the property - ie true or false. Instead pass the section name as a string, and refer to the property in the scope using the name.

btw - A better idea would be to create a directive that encapsulates the behavior, and will help you stays DRY.

$scope.toogleSection = function(sectionName) {
  if ($scope[sectionName]) {
    $scope[sectionName] = false;
  } else {
    $scope[sectionName] = true;
  }
};

$scope.toogleSection('toogleShowName');

Upvotes: 1

yvesmancera
yvesmancera

Reputation: 2925

You can refactor it so you can send the name of the property as a parameter to the function, like this:

$scope.toggleSelection = function(sectionName) {
  $scope[sectionName] = !$scope[sectionName];
};

Upvotes: 1

Related Questions