0

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.

2
  • What's wrong with the above? Commented Sep 25, 2015 at 20:52
  • The variable "data" is updated but the scope variable itself (controller.data.variable) isn't. Commented Sep 25, 2015 at 20:56

1 Answer 1

2

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'");
    }
  };
});
Sign up to request clarification or add additional context in comments.

2 Comments

I also tried this, but the problem is that the variable is multidimensional. Something like settings.section.value, so accessing it like this doesn't work either (at least how I tried it)
@Marco I've updated the answer, but it's not pretty :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.