Marco
Marco

Reputation: 31

AngularJS change scope variable on ng-click passing the variable in a function

Okay I have multiple scope variables. I pass them into a toggle function like this.

<button ng-click="controller.toggle(controller.data.variable)">Change</button>

On click I want to change the variable like this

controller.toggle = function(data) {
    if(toggled) {
        data = 'test';
    }
}

Is there any way to achieve this?

I have already searched for solutions but found nothing.

Upvotes: 0

Views: 2345

Answers (1)

o4ohel
o4ohel

Reputation: 1789

Does this help?

HTML:

<div ng-controller="MainCtrl">

  <div>
    <button ng-click="toggle('variable1')">Change Variable 1</button>
  </div>

  <div>
    <button ng-click="toggle('variable2')">Change Variable 2</button>
  </div>

  <pre>variable1: {{variable1}}</pre>
  <pre>variable2: {{variable2}}</pre>
</div>

JS:

angular.module('myApp', []).controller('MainCtrl', function($scope) {
  $scope.variable1 = 'on';
  $scope.variable2 = 'off';

  $scope.toggle = function(propName) {
    var val = $scope[propName];
    $scope[propName] = val === 'on' ? 'off' : 'on';
  };
});

UPDATED example (please don't hate me for using eval)

html:

<div ng-controller="MainCtrl">
  <div>
    <button ng-click="toggle('settings.section.value1')">Change Variable 1</button>
  </div>
  <div>
    <button ng-click="toggle('settings.section.value2')">Change Variable 2</button>
  </div>

  <pre>variable1: {{settings.section.value1}}</pre>
  <pre>variable2: {{settings.section.value2}}</pre>
</div>

js:

angular.module('myApp', []).controller('MainCtrl', function($scope) {
  $scope.settings = {
    section: {
      value1: 'on',
      value2: 'off'
    }
  };

  $scope.toggle = function(prop) {
    var val = eval("$scope." + prop);
    if(val === 'on') {
      eval("$scope."+ prop +"= 'off'");
    } else {
      eval("$scope."+ prop +"= 'on'");
    }
  };
});

Upvotes: 2

Related Questions