5

我有简单的控制器代码:

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

谁能告诉我为什么以及如何使它工作?

谢谢

4

3 回答 3

6

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

IE

$scope.showErrorAlert = { value: false };

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

或者您可以重构 switchBool 代码以对 $scope 本身进行操作。你需要硬编码或抽象“showErrorAlert”,很难。取决于你的要求。

于 2013-06-30T12:35:18.957 回答
5

其他人已经给了你一个正确的答案,为什么传递的变量在范围上没有改变。但是,如果您的实际用例只是切换布尔值,那么至少还有其他两种更简单的方法可以实现这一点:

a) 直接在 ngClick 表达式中切换变量:

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

b) 通过将变量名称传递给通用“switch”函数来切换变量:

<button type="button" ng-click="switchBool('showErrorAlert')">×</button>
$scope.switchBool = function(var){
  $scope[var] = !$scope[var];
};
于 2013-06-30T13:28:13.657 回答
2
$scope.showErrorAlert = false;


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

当您将值传递给 时switchBool,它是按值传递的,而不是引用传递。因此,该值仅在该函数内更改。

您可以尝试将 var 名称传递给它,$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
于 2013-06-30T12:31:57.647 回答