尝试将Angular UI Bootstrap Typeahead与Alert结合使用

时间:2013-07-20 00:44:01

标签: angularjs typeahead angular-ui-bootstrap

我正在尝试获取预先输入的结果并将其粘贴到引导警报中。我希望用户能够从typeahead选择中多次选择,并创建多个引导警报。

这是我的样本。目前这两个问题是:

  1. 警报不起作用,即使是样本
  2. 也是如此
  3. 警报和预先不会互相交谈

    jsfiddle

  4. 我的HTML:

    <body ng-app="testApp">
    
    <div class='container-fluid' ng-controller="TypeaheadCtrl">
        <pre>Choice: {{selected| json}}</pre>
        <input type="text" ng-model="selected" typeahead="sample for sample in samples | filter:$viewValue">
    </div>
    
    <div ng-controller="AlertDemoCtrl">
      <alert ng-repeat="alert in alerts" type="alert.type" close="closeAlert($index)">{{alert.msg}}</alert>
      <button class='btn' ng-click="addAlert()">Save Choice</button>
    </div>
    
        </body>
    

    我的JS:

    angular.module('testApp', ['ui.bootstrap']);
    
    function TypeaheadCtrl($scope) {
    
      $scope.selected = undefined;
      $scope.samples = ["foo","bar","blah","foobar","blahblah"];
    }
    
    function AlertDemoCtrl($scope) {
         $scope.alerts = undefined;
        /* $scope.alerts = [
        { type: 'error', msg: 'Oh snap! Change a few things up and try submitting again.' }, 
        { type: 'success', msg: 'Well done! You successfully read this important alert message.' }
      ];*/
    
      $scope.addAlert = function() {
        $scope.alerts.push({msg: "Another alert!"});
      };
    
      $scope.closeAlert = function(index) {
        $scope.alerts.splice(index, 1);
      };
    
    }
    

    用户选择建议的自动完成后,将使用以下内容显示用户选择的结果:{{selected | JSON}}。我希望选择留在DOM中,并允许用户再选择一个项目。然后我想让用户能够删除一个选项(单击按钮或[x])。

    在我看来,实现这一点的一种方法是使用(ui.bootstrap.alert)来记录用户的选择。

    如果不使用Alert就可以做到这一点,那也没关系。

1 个答案:

答案 0 :(得分:3)

来自http://angular-ui.github.io/bootstrap/的指令的好处在于它们是原生的AngularJS指令,可以很容易地组合在一起。事实证明,使用typeahead指令的alert属性将typeahead-on-selecttypeahead指令组合在一起非常容易。通过使用typeahead-on-select,您可以指定在typeahead中进行选择时要调用的回调。

以下是HTML示例:

<input type="text" ng-model="selected" typeahead-on-select="selectMatch($item)" typeahead="state for state in states | filter:$viewValue | limitTo:10">

和回调函数(selectMatch):

$scope.selectMatch = function(selection) {
    $scope.alerts.push({msg: selection});
    $scope.selected = '';
};

正如您所看到的,在选择新匹配时推送新警报非常容易。然后,您只需显示警报:

<alert ng-repeat="alert in alerts" type="alert.type" close="closeAlert($index)">{{alert.msg}}</alert>

我不确定在将typeaheadalert指令组合在一起时遇到的确切问题是什么,所以这里有一个工作代码,用于演示上面描述的内容: http://plnkr.co/edit/i2x5csbrW1uKSISt2fqW?p=preview