【问题标题】:How do I pass the contents of a textbox into angular js as an input parameter, rather than a $scope variable?如何将文本框的内容作为输入参数而不是 $scope 变量传递给 angular js?
【发布时间】:2021-12-19 02:16:06
【问题描述】:

目前,我知道如何从文本框中收集输入并将其用于$scope 变量。但是如果我不想使用$scope 变量怎么办?如果我只是想将输入作为参数传递给函数怎么办?

目前:

我有一些看起来像这样的 JSP:

<textarea
  required="true"
  spellcheck="on"
  data-ng-model="editTools.productDescription"
  rows="4"
>
</textarea>

我在 JSP 中也有一个按钮,它调用 Angular JS 中的函数:

<button 
  id="description-submit-button"
  data-ng-click="mySpecialFunction()"
  buttonType="${'primary'}"
  htmlButtonType="${'button'}"
>
  <text>"Submit"</text>
</button>

所以,我知道这是可行的。我正在为$scope.editTools.productDescription 分配一个值,然后mySpecialFunction() 使用该值。

但是如果不使用$scope 变量,我将如何完成同样的事情呢?我希望能够说类似data-ng-click="mySpecialFunction({the stuff the user typed in the text box})"

这可能吗?怎么样?

【问题讨论】:

    标签: javascript html angularjs jsp


    【解决方案1】:

    您实际上不必在控制器中声明模型变量。您可以将您的 textarea 更改为此,以便模型为 myVariable(您可以随意命名):

    <textarea
        required="true"
        spellcheck="on"
        data-ng-model="myVariable"
        rows="4">
    </textarea>
    

    然后您可以将myVariable 直接传递到HTML 中的mySpecialFunction 调用中,如下所示:

    <button 
      id="description-submit-button"
      data-ng-click="mySpecialFunction(myVariable)"
      buttonType="${'primary'}"
      htmlButtonType="${'button'}"
    >
      <text>"Submit"</text>
    </button>
    

    现在在您的控制器中,您的函数将如下所示:

    $scope.mySpecialFunction = function (value) {
        // value === myVariable
        // do something with it here
    };
    

    但请注意,angularjs 实际上确实在幕后将myVariable 添加到$scope,因此,如果您真的想要,您仍然可以在控制器中使用$scope.myVariable 访问该值。

    【讨论】:

    • 谢谢,这解决了我想知道的一切!
    • 另外:听起来没有办法将变量作为参数传递给函数没有也在幕后将它添加到$scope
    猜你喜欢
    • 2014-07-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-17
    • 2015-12-31
    • 2013-08-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多