In AngularJS how to use datalist

2020-06-01 06:20发布

问题:

<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>

<div ng-app="" ng-controller="cntryController">
    <input list="testList" type="" ng-model="SelectedDoctor" ng-change="LoadSessionData(SelectedDoctor)" />
    <datalist id="testList">
        <option value="Dr.Test1" ng-selected="selected"></option>
        <option value="Dr.Test2"></option>
        <option value="Dr.Test2"></option>
    </datalist>
</div>

Controller

function cntryController($scope) {
    $scope.LoadSessionData = function(val) {
        console.log(val);
    };
}

check this Link http://jsbin.com/jifibugeke/1/edit?html,js,console,output

Above mention datalist sample code and URL using angularjs, here my problem is what ever i am typing the text box, in controller add by added every words,in my requirement in datalist selected details only shows in controller,

回答1:

//here your html
<div ng-app="myapp1" ng-controller="cntryController">
    <input list="testList" type="" ng-model="SelectedDoctor" ng-change="LoadSessionData(SelectedDoctor)" />
    <datalist id="testList">
        <option ng-repeat="x1 in names" value="{{x1.drname}}">
    </datalist>
</div>

//here your script        
<script>
    var app=angular.module('myapp1',[]);
    app.controller('cntryController',function ($scope) {
//data for ng-repeat
    $scope.names=[{'drname':'Dr.Test1'},{'drname':'Dr.Test2'},{'drname':'Dr.Test3'}]
    $scope.LoadSessionData = function(val) {
//console log
        console.log(val);
    }
});
</script>


回答2:

This is right way for angular:

<input list="Calle" type="text" ng-model="xCalle"  >
    <datalist name="Calle" id="Calle" >
        <option value="11 DE SEPTIEMBRE DE 1888">
        <option value="12 DE OCTUBRE">
    </datalist>

Watch type="text" and where the name, id and ng-model are placed.

That will work with angular without any javascript additional function.