【问题标题】:Angular UI bootstrap typeahead, ng-model changing from object to stringAngular UI bootstrap typeahead,ng-model从对象更改为字符串
【发布时间】:2017-06-09 08:09:05
【问题描述】:

我遇到了 UI 引导 Typeahead 的问题。这里是plnkr,下面是解释。

http://plnkr.co/edit/lvy1Xu13xfFBjHbIY68H?p=preview

我希望能够从 Typeahead 列出的状态中选择一种状态,但也希望能够通过写入不存在的状态名称以具有属性名称和标志的相同形式创建新状态。

当您从 Typeahead 中选择一个状态时,一切都会按预期进行。您选择整个对象,属性“状态”和“标志”也被选中。当您编写的字符串与 Typeahead 中列出的任何选项都不匹配时,就会出现问题。假设您要设置状态“myState”,那么 ng-model 是字符串,而不是当您从 typeahead 中选择一个选项时的对象,并且无法输入标志属性,因为您无法在字符串上创建属性。

有什么方法可以让我更改 uib-typeahead 设置或以某种方式更改 ng-model,制作一些将 ng-model 从字符串更改为对象的函数,或类似的东西?

<input type="text" ng-model="customPopupSelected" placeholder="state" uib-typeahead="state as state.name for state in statesWithFlags | filter:{name:$viewValue}" typeahead-popup-template-url="customPopupTemplate.html" class="form-control">

<input type="text" ng-model="customPopupSelected.flag" placeholder="flag" class="form-control"> 

这是对我想要实现的目标的简化说明。当我从 Typeahead 中选择状态时,状态如下所示:

state = { 
  "name": "Arizona",
  "flag": "9/9d/Flag_of_Arizona.svg/45px-Flag_of_Arizona.svg.png"
}

当我开始输入并输入一个不存在的状态时,状态是一个字符串。

state = "myState"

所以我无法添加新的“state.name”,然后将“state.flag”属性添加到状态对象。所以我想以某种方式解决这个问题,如果可能的话,我能够创建自己的状态。

state = { 
  "name": "myState",
  "flag": "mystate-flag.svg.png"
}

【问题讨论】:

    标签: angularjs angular-ui-bootstrap bootstrap-typeahead


    【解决方案1】:

    使用 Uib-typeahead 添加 typeahead-editable="false"

    <input typeahead-editable="false" type="text" ng-model="customPopupSelected" placeholder="state" uib-typeahead="state as state.name for state in statesWithFlags | filter:{name:$viewValue}" typeahead-popup-template-url="customPopupTemplate.html" class="form-control">
    
    <input type="text" ng-model="customPopupSelected.flag" placeholder="flag" class="form-control">
    

    希望对你有帮助。

    【讨论】:

    • 这不是我想要的。也许我的解释不够好。那我会尽量解释得更好,
    • us per description in type-ahead if enter char not found then it's not return object it return string 但在使用给定条件后,如果您未在列表中选择建议项目或未找到,则返回 null
    【解决方案2】:

    您可以添加$scope.$watch:

    // listen to customPopupSelected variable changes
    $scope.$watch('customPopupSelected', function (nVal) {
      // enter this block only if new value is not an object
      if (nVal && angular.isString(nVal)) {
        // convert customPopupSelected from a string to desired object
        $scope.customPopupSelected = {
          name: nVal,
          flag: 'URL-TO-SOME-DEFAULT-FLAG'
        };
      }
    });
    

    这是您更新后的插件:http://plnkr.co/edit/jezOW8SEJUh59CzwFpr8?p=preview

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-06
      • 1970-01-01
      • 2013-04-09
      相关资源
      最近更新 更多