javascript - 为什么不能使用 "switch"技术从 HTML 更改范围值?

标签 javascript angularjs

我有简单的 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/

相关文章:

javascript - node.js 需要太多的 TCP 套接字

javascript - 如何在 jQuery 中获取 parent 的特定下一个和 previous sibling 姐妹的 child ?

angularjs - Ionic 选项卡在选项卡之间显示白色背景几分之一秒

javascript - 使用 karma 在 angularjs 中进行测试时获取 'require is not defined'

angularjs - 从 PouchDB(或 CouchDB)获取随机文档

angularjs - 如何使用 Angular 数据表呈现具有模型绑定(bind)的列?

javascript - Angular UI 路由器 View 不显示任何内容

javascript - 如何对 bootstrap-3 分页进行编程以处理简单的 HTML 内容

javascript - ngClass 什么时候评估函数/如何在自定义指令中模仿它

javascript - lodash递归查找数组中的项目