AngularJS在ng-click上更改范围变量,在函数中传递变量

时间:2015-09-25 20:50:10

标签: angularjs variables onclick scope

好的,我有多个范围变量。 我将它们传递给这样的切换功能。

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

点击我想改变这个变量

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

有没有办法实现这个目标?

我已经搜索了解决方案,但一无所获。

1 个答案:

答案 0 :(得分:2)

this有帮助吗?

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';
  };
});

更新example(请不要因为使用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'");
    }
  };
});