Angular Js- 为什么点击值没有被选中?

Angular Js- Why on click the value is not selected?

我正在使用下拉菜单中的图像实现预先输入,问题是当我单击下拉菜单中的项目时,它没有被选中。

<body ng-app="TypeaheadDemo">
  <script type="text/ng-template" id="customTemplate.html">
    <a>
      <img ng-src="{{match.model.img}}" width="16"> {{match.model.name}}
    </a>
  </script>

  <div class="container-fluid" ng-controller="TypeaheadCtrl">
    <h1>Angular UI Bootstrap Typeahead</h1>
    <input type="text" ng-model="query" class="form-control" typeahead="name as result.name for result in results | filter:{name:$viewValue}" typeahead-template-url="customTemplate.html" />
  </div>
</body>

    angular.module("TypeaheadDemo", ['ui.bootstrap'])
  .controller('TypeaheadCtrl', ['$scope', function($scope) {

    $scope.results = [{
      name: "California",
      img: "https://upload.wikimedia.org/wikipedia/commons/thumb/0/01/Flag_of_California.svg/45px-Flag_of_California.svg.png"
    }, {
      name: "Delaware",
      img: "https://upload.wikimedia.org/wikipedia/commons/thumb/c/c6/Flag_of_Delaware.svg/45px-Flag_of_Delaware.svg.png"
    }, {
      name: "Florida",
      img: "https://upload.wikimedia.org/wikipedia/commons/thumb/f/f7/Flag_of_Florida.svg/45px-Flag_of_Florida.svg.png"
    }];
  }]);

这是 jsfiddle 的 link http://jsfiddle.net/pqe3pf89/

您的表达式构建不正确,如果您愿意,可以使用 select as 但不是那样。您这样做的方式 select 对您的模型没有任何影响。

为了让您的代码正常工作,您可以将您的表达式更改为如下代码:它将 select result.name 作为您的 ngModel 的值,并将通过以下方式过滤您的列表使用 $viewValue.

您的 result 项目值的 属性 name
typeahead="result.name for result in results | filter:{name: $viewValue}"

@Lenilson de Castro 是正确的,但这只会将 $scope.query 绑定到所选结果的名称 属性... 即 "California"、"Florida"、。 ..

如果您想将 $scope.query 绑定到完整的结果对象,您可以使用:

typeahead="result as result.name for result in results | filter:{name: $viewValue}"