Angularjs Angular UI引导程序typeahead,ng模型从对象更改为字符串
我对UI引导类型有问题。这是plnkr,解释如下 我希望能够从Typeahead列出的状态中选择一个状态,但也能够以相同的形式创建新状态,通过写入不存在的状态名称,使用属性名称和标志 当您从Typeahead中选择一个状态时,一切都按预期工作。选择整个对象,属性“state”和“flag”也会被选中。当您编写的字符串与Typeahead中列出的任何选项都不匹配时,就会出现问题。假设您想使状态为“myState”,那么ng模型是字符串,而不是像您从typeahead中选择一个选项时那样的对象,并且无法输入flag属性,因为您无法在字符串上创建属性 是否有任何方法可以改变uib的typeahead设置或以某种方式改变ng模型,制作一些函数将ng模型从字符串更改为对象,或者类似的东西Angularjs Angular UI引导程序typeahead,ng模型从对象更改为字符串,angularjs,angular-ui-bootstrap,bootstrap-typeahead,Angularjs,Angular Ui Bootstrap,Bootstrap Typeahead,我对UI引导类型有问题。这是plnkr,解释如下 我希望能够从Typeahead列出的状态中选择一个状态,但也能够以相同的形式创建新状态,通过写入不存在的状态名称,使用属性名称和标志 当您从Typeahead中选择一个状态时,一切都按预期工作。选择整个对象,属性“state”和“flag”也会被选中。当您编写的字符串与Typeahead中列出的任何选项都不匹配时,就会出现问题。假设您想使状态为“myState”,那么ng模型是字符串,而不是像您从typeahead中选择一个选项时那样的对象,并
<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">
当我开始键入一个不存在的状态时,状态是一个字符串
state=“myState”
所以我无法添加新的“state.name”,然后将“state.flag”属性添加到state对象。所以,我想以某种方式绕过这个问题,如果可能的话,我可以创造自己的状态
state = {
"name": "myState",
"flag": "mystate-flag.svg.png"
}
将typeahead editable=“false”与Uib typeahead一起添加
<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">
我希望这将对您有所帮助。您可以添加一个
$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'
};
}
});
这是您更新的plunker:这不是我想要的。也许我的解释不够好。我将尝试更好地解释,如果未找到enter char,则它不是返回对象,而是返回字符串,但在使用给定条件后,如果您未在列表中选择“建议项”或“未找到”,则它将返回null
// 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'
};
}
});