Angularjs ng-model with option list

Hangul

New Member
#1
I am trying to bind the ng-model "pick" from the option list into the typeahead, is there a way to do so?

HTML code:
Mã:
        <select ng-model="pick">
            <option value="cnames">NAME</option>
            <option value="caddress">Address</option>
            <option value="cpostal">PostalCode</option>
        </select>
        <input type="text" ng-model="selected" uib-typeahead="cname for cname in pick | filter:$viewValue | limitTo:5">
        <a href="#!/searchFeature"><button ng-click="myFunc(selected)">Search</button></a>
I wan the uib-typeahead "pick" value to change accordingly to the selected value from the option list. For e.g if NAME is chosen, the "pick" value in the uib-typeahead will change to cnames.
 

Admin

Administrator
Thành viên BQT
#2
Assuming cnames, caddress and cpostal correspond to collections of elements (e.g. string), the only change you'll need to make is to ensure that the option elements use ng-value instead of value. The latter will bind the literal string value, whereas the former will bind the collection as you'd expect.
Mã:
angular
  .module('app', ['ui.bootstrap'])
  .controller('ctrl', function ($scope) {
    $scope.cnames = ['cname1', 'cname2', 'cname3'];
    $scope.caddress = ['caddress1', 'caddress2', 'caddress3'];
    $scope.cpostal = ['cpostal1', 'cpostal2', 'cpostal3'];
  });
Mã:
<link rel="stylesheet" href="https://unpkg.com/bootstrap@3.3.7/dist/css/bootstrap.min.css">
<div
  ng-app="app"
  ng-controller="ctrl">
  <select
    ng-model="pick"
    class="form-control">
    <option ng-value="cnames">NAME</option>
    <option ng-value="caddress">Address</option>
    <option ng-value="cpostal">PostalCode</option>
  </select>
  <input
    type="text"
    class="form-control"
    ng-model="selected"
    uib-typeahead="cname for cname in pick | filter:$viewValue | limitTo:5">
</div>
<script src="https://unpkg.com/angular@1.7.5/angular.min.js"></script>
<script src="https://unpkg.com/angular-ui-bootstrap@2.5.6/dist/ui-bootstrap-tpls.js"></script>
 

Từ khóa phổ biến

You are using an out of date browser. It may not display this or other websites correctly.
You should upgrade or use an alternative browser.

Top