2013-06-30 20 views
5

我有简单的控制器代码:为什么范围值不能通过使用“切换”技术从HTML更改?

JS

$scope.showErrorAlert = false; 


$scope.switchBool = function(value) { 
    value = !value; 
}; 

HTML

<div class="alert alert-error" ng-show="showErrorAlert"> 
       <button type="button" class="close" data-ng-click="switchBool(showErrorAlert)" >×</button> 
       <strong>Error!</strong> {{errorTextAlert}} 
      </div> 

从代码片段你可以看到,我试图改变$scope.showErrorAlert值。

但是它不起作用,value更改但不是showErrorAlert

有人可以告诉我为什么以及如何使它工作吗?

谢谢

+0

+1你的问题很好:) –

回答

5

其他人已经给你一个正确的答案,为什么传递的变量没有在范围上改变。但是,如果你真正的用例仅仅是切换布尔值之外还有实现这个目的的至少两个其他更简单的方法:

一)切换直接ngClick表达式中的变量:

<button type="button" ng-click="showErrorAlert = !showErrorAlert">×</button> 

b )通过传递变量名到一个通用的“开关”功能切换变量:

<button type="button" ng-click="switchBool('showErrorAlert')">×</button> 
$scope.switchBool = function(var){ 
    $scope[var] = !$scope[var]; 
}; 
+0

好例子(b)'$ scope [var] =!$ scope [var];',谢谢 –

2
$scope.showErrorAlert = false; 


$scope.switchBool = function(value) { 
    value = !value; 
}; 

当值传递给switchBool,它是按值传递,而不是引用。所以该值只在该函数内发生变化。

你可以尝试通过它的变种名称,如$scope.showErrorAlert然后做内switchBool是这样的:

eval(value + " = !" + value); 
在行动

http://jsfiddle.net/Npp2N/1/

$scope.showErrorAlert = false; 
$scope.switchBool = function(value) { 
    eval(value + " = !" + value); 
}; 

console.log($scope.showErrorAlert); // false 
$scope.switchBool("$scope.showErrorAlert"); 
console.log($scope.showErrorAlert); // true 
6

JS按值传递的参数。传递引用的简单替代方法是传递一个对象(而不是属性本身)。

I.e.

$scope.showErrorAlert = { value: false }; 

$scope.switchBool = function(obj) { 
    obj.value = !obj.value; 
}; 

或者你可能重构switchBool代码在$范围本身进行操作。你需要硬编码或抽象“showErrorAlert”,然后,艰难。取决于你的要求。

+2

没有必要宣布新的对象语法只使用$ scope.sh owErrorAlert = {value:false} –