是否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'");
}
};
});
這有什麼錯以上? – tymeJV
變量「data」已更新,但範圍變量本身(controller.data.variable)不是。 – Marco