okay have multiple scope variables. pass them toggle function this.
<button ng-click="controller.toggle(controller.data.variable)">change</button>
on click want change variable this
controller.toggle = function(data) { if(toggled) { data = 'test'; } }
is there way achieve this?
i have searched solutions found nothing.
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 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'"); } }; });
Comments
Post a Comment