【问题标题】:angularjs form input suggestionsangularjs表单输入建议
【发布时间】:2014-04-30 16:36:35
【问题描述】:

我对 angularjs 中的表单有疑问。

经典 html & php 示例

    <form name="myForm" action="post.php" method="post" autocomplete="on">
        <input name="namename" type="text" />
        <input name="email" type="text" />

        <input name="submit" type="submit" value="submit" />
    </form>

按预期工作。第二次访问时,第一次提交表单后,我只需要输入第一个字母,输入字段就会根据第一个帖子提示一些内容。

angular中的相同形式。

    <form name="myForm" ng-submit="test(user)" autocomplete="on">
        <input name="name" type="text" ng-model="user.name" autocomplete="given-name" />
        <input name="email" type="text" ng-model="user.email" />

        <input name="submit" type="submit" value="submit" />
    </form>

第二次访问时,表格什么也没有,这很烦人。

有什么解决办法吗?

例子

提前致谢。

【问题讨论】:

    标签: javascript php forms angularjs


    【解决方案1】:

    您所描述的行为是由浏览器完成的,不能保证在所有情况下都有效。在 AngularJS 中实际上很容易做到;只需跟踪共享状态对象。这可以通过多种方式完成,最简单的方法是使用 value provider,如下所示:

    // Create an injectable object with the name 'userInput'
    angular.module('myApp').value('userInput', {});
    

    现在注入这个对象在处理表单的控制器中:

    angular.module('myApp').controller('MyController', function($scope, userInput) {
      // Assign the state object to the scope so it's available for our view
      $scope.user = userInput;
    });
    

    像你一样渲染表单,你会看到表单的状态被保留了。事实上,这是使用 Angular 编程时隐藏的宝石之一,因为它允许您保留非常复杂的状态信息,这在以前是非常不切实际的。

    Live demo can be found in this plunker.

    编辑

    让自动完成功能发挥作用的一种方法是维护 datalist 元素。只需将先前输入的值存储在一个数组中,然后使用ng-repeat 来呈现所有选项。使用 list 属性将输入元素与数据列表相关联,一切顺利。

    <input list="nameHistory" type="text" ng-model="user.name" />
    
    <datalist id="nameHistory">
      <option ng-repeat="item in userHistory.name" value="{{ item }}"></option>
    </datalist>
    

    Live demo can be found in this plunker.

    【讨论】:

    • 感谢您的回答,但这不是我的意思。我不想保存表单的状态。每个 Broser 都有一个内置表单自动填充常见输入字段(如用户名等)的历史记录。这就是我想要使用的,但是如果表单实际上执行了一个帖子,chrome 只会保存这个自动填充数据,这不是由 angular 完成的。我在上面的帖子中添加了一张图片。
    • 哦,我的错:S ...我已经用一个可能的解决方案更新了答案,并提供了一个免费的 plunker 演示。
    【解决方案2】:

    只需在输入标签中添加此属性autocomplete="off"

    【讨论】:

    • 感谢您提供答案!你能补充一点细节吗?
    猜你喜欢
    • 1970-01-01
    • 2011-09-21
    • 2011-07-29
    • 1970-01-01
    • 1970-01-01
    • 2017-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多