angularjs – 使用Angular UI Directive Typeahead重定向到链接

前端之家收集整理的这篇文章主要介绍了angularjs – 使用Angular UI Directive Typeahead重定向到链接前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在为项目使用Angular UI Bootstrap typeahead指令,我想根据typeahead中选择的内容重定向到动态URL.我正在尝试将typeahead用作搜索框.

我查看了文档(尝试RTFM),所以我知道有一个我可以使用的typeaheadOnSelect属性,但我不知道如何将其与链接联系起来.我正在使用对象的JSON文件,每个对象都有一个特定的ID.我希望能够直接在typeahead属性链接,如下所示:

<div class='container-fluid' ng-controller="TypeaheadCtrl">
        <input type="text" id="search" ng-model="selectedPerson" typeahead="person as person.name for person in person | filter:$viewValue" typeahead-min-length="3" typeaheadOnSelect="#/100_Ages/{{person.id}}" ng-init="" />
    </div>

但那没用.我想我需要一个特定的控制器,但我不确定. typeahead指令似乎工作得很好,所以我想有一个简单的解决方案,但我找不到它.

现在,我的Typeahead控制器看起来像这样:

function TypeaheadCtrl($scope,$http) {
  $http.get('person.json').success(function(data) {
      $scope.person = data;
      });
}

This plunkr显示了一切都在行动.我的路由器是使用基于每个JSON id的动态URL设置的,如下所示:

angular.module('app',['ui.bootstrap']).
    config(['$routeProvider',function($routeProvider) {
    $routeProvider.
        when('/app/:personId',{templateUrl: 'partials/person.html',controller: DetailCtrl}).
    }]);

解决方法

您可以观察对selectedPerson模型的更改.这是一个例子:

function TypeaheadCtrl ($scope,$http,$location,$log,$timeout) {
  $http.get('person.json').success(function(data) {
      $scope.person = data;
  });
  $scope.$watch('selectedPerson',function(newValue,oldValue) {
    if (newValue){
      $log.info('/100_Ages/' + $scope.selectedPerson.id);
      $location.path('/100_Ages/' + $scope.selectedPerson.id);
    }
  });
}

更新:更新到v0.4.0后,我能够这样做:

function TypeaheadCtrl ($scope,$timeout) {
  $http.get('person.json').success(function(data) {
      $scope.people = data;
  });
  $scope.onSelect = function($item,$model,$label){
    $scope.$item = $item;
    $scope.$model = $model;
    $scope.$label = $label;
    $log.info($scope.$item);
    $log.info($scope.$model);
    $log.info($scope.$label);
    $location.path('/person/' + $scope.$item.id);
  }
}

然后在HTML中,我这样做了:

<input type="text" id="search" placeholder="Search for a name or age" ng-model="selectedPerson" typeahead="person.id as person.name for person in people | filter:$viewValue" typeahead-on-select="onSelect($item,$label)" typeahead-min-length="3" ng-init="" />

猜你在找的Angularjs相关文章