angularjs form input suggestions

2020-04-20 03:35发布

问题:

I have a problem with a form in angularjs.

Example with classic 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>

which works as expected. On the second visit, after i submitted the form for the first time, i just need to type the first letter and the input field will suggest something based on the first post.

The same form in 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>

On the second visit here the form will suggest nothing at all, which is very irritating.

Is there any fix for that?

Example

thanks in advance.

回答1:

That behaviour you're describing is done by the browser and is not guaranteed to work in all situations. It's actually quite easy to do in AngularJS; just keep track of a shared state object. This can be done in several ways, the most easiest by using the value provider like this:

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

Now inject this object in the controller that is handling the form like this:

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;
});

Render the form as you did and you'll see that the state of the form is kept. In fact, this is one of the hidden gems when programming with Angular since it allows you to keep very complex state information, which was previously pretty impractical.

Live demo can be found in this plunker.

Edit

One way to get the autocomplete to work is to maintain datalist elements. Just store the previous entered values in an array and use a ng-repeat to render all the options. Associate the input element with the datalist using the list attribute and you'r good to go.

<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.



回答2:

Just add to the input tag this attribute autocomplete="off"