我有简单的 Controller 代码:
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
没有变化。
有人能告诉我为什么以及如何让它工作吗?
谢谢
最佳答案
JS按值传递参数。通过引用传递的一个简单替代方法是传递一个对象(而不是属性本身)。
即
$scope.showErrorAlert = { value: false };
$scope.switchBool = function(obj) {
obj.value = !obj.value;
};
或者您可以重构 switchBool 代码以对 $scope 本身进行操作。然后,您需要硬编码或抽象“showErrorAlert”,这很困难。取决于您的要求。
关于javascript - 为什么不能使用 "switch"技术从 HTML 更改范围值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17390349/