javascript - AngularJS 传递范围?

标签 javascript html angularjs

我实际上不确定问题的标题应该是什么,因为我不清楚我错过了什么。

我将其归结为一个非常简单的示例(实际情况更为复杂)。我在 ng-switch 内有一个文本框和按钮。我读过,该开关创建了自己的本地范围。

我想要在单击按钮时将文本框的值传递给函数。在函数中,我将对该值执行需要执行的操作,然后清除文本框。我正在努力寻找正确的方法来做到这一点。

Controller 代码:

$scope.temp = 1;

$scope.tempCall = function (tempModel) {
    tempModel = ""; //this doesn't work
    $scope.tempModel = ""; //nor does this
};

HTML/模板:

<div ng-switch on="temp">
    <div ng-switch-when="1">
        <input ng-model="tempModel" />
        <input type="button" ng-click="tempCall(tempModel)" />
    </div>
    <div ng-switch-when="2">TWO</div>
</div>

我相信我实际上可以从父作用域或根作用域遍历作用域并清除该值,但这“感觉”不正确。清除该值的正确( Angular )方法是什么?

最佳答案

当您在 Angular 作用域中使用原始值时,无法从子作用域覆盖父作用域中的值。这是因为 Angular 使用 JavaScript 原型(prototype)继承。

在这种情况下,您可以做的是在父作用域中创建一个对象,然后您可以更新子作用域中的值。因为您没有覆盖对象(仅附加到它的属性),所以引用有效。

我在 plunk 上创建了一个演示,你可以 view it here

$scope.temp = 1;
$scope.tempModel = {};

$scope.tempCall = function () {
  $scope.tempModel.previous = $scope.tempModel.value
  $scope.tempModel.value = "";
};

<div ng-switch on="temp">
  <div ng-switch-when="1">
      <input ng-model="tempModel.value" />
      <input type="button" ng-click="tempCall()" />
      {{tempModel.previous}}
  </div>
  <div ng-switch-when="2">TWO</div>

关于javascript - AngularJS 传递范围?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17088965/

相关文章:

javascript - MutationObserver 观察 jquery 追加?

php - 检查 cookie - 如果找到显示链接

javascript - 鼠标悬停时工具提示未正确显示

javascript - jQuery 智能菜单在 Angularjs 中不起作用

javascript - Bootstrap Accordion - 导航离开后保持打开/关闭?

javascript - AngularJS 中的路由

javascript - 在 Typescript 中使用 Object.keys 时避免隐式 'any' 类型

javascript - 当元素未运行时在 C# 中获取 HTML 内部 HTML ="server"

html - 相对位置不包含绝对定位元素

angularjs - Canvas 如何与 MVC 框架一起使用?