我想知道如何从 bootstrap typeahead 生成的下拉列表中选择一个选项时调用控制器函数。下拉列表中的每个项目都有一个唯一的 ID。选择选项时,我需要将其传递给其他函数。
HTML:
<div class="container-fluid" ng-app="stock" ng-controller="mainCtrl as main">
<h2>Stock Search</h2>
<input type="text" ng-model="val" placeholder="Search for a stock" uib-typeahead="obj as obj.name for obj in result | filter:$viewValue | limitTo:10" ng-keydown="main.getStock(val)" typeahead-no-results="noResults" class="form-control" my-enter="main.getDetails(result)">
<div ng-show="noResults">
<i class="glyphicon glyphicon-remove"></i> No Results Found
</div>
</div>
JavaScript:
angular.module('stock', ['ui.bootstrap'])
.config(['$qProvider', function ($qProvider) {
$qProvider.errorOnUnhandledRejections(false);
}])
.directive('myEnter', function () {
return function (scope, element, attrs) {
element.bind("keydown keypress", function (event) {
if(event.which === 13) {
scope.$apply(function (){
scope.$eval(attrs.myEnter);
});
event.preventDefault();
}
});
};
})
.controller('mainCtrl', function($scope, $http){
var app = this;
app.config = {
headers: {
'User-ID': 379,
'Access-Token':'eWEyOS5HbHNwQkRCVUJPX2d0UUNGUVR4Z1NKRTgzUkdCWHB2V1NCbWwtckNHWW5iS05NSjJLY0J5YU5CeU5QWFhTU3R5N1phdTctd250aW15dk5ZUFcySEt3ckpxNUdCNFhwQzYyNGVQcnlKSWlYa21Fa0xvQ0hIZ1kxZVRjaU0wJVVTRVIlMzc5',
'User-IP':'0.0.0.0',
'Agent':'agent'
}
};
$scope.result = [];
this.getStock = function(val){
$http.get("https://staging.investo2o.com/assetmanager-ws/api/v1/assets/getassets?query="+val+"&assetType=STK", app.config)
.then(function(response){
$scope.result = response.data;
return $scope.result;
});
}
this.getDetails = function(id){
console.log(id);
}
})//end of ctrl
我该怎么做呢?
当您要求 attrs.myEnter 时,它只是一个包含您的表达式的字符串。scope.$eval 获取该字符串并根据范围对其进行评估。但我认为 $eval 并不是为了获取包含函数的字符串并实际执行该函数。更多的是能够用更短的语法报告存在于范围内的值。如果你想走那条路,看看 $parse 服务。
但是,您可能“应该”这样做的方式是向指令定义对象添加范围属性,您可以将 myEnter 设置为“&”,然后它会在scope.myEnter
. 运行该函数时,就像运行 my-enter 属性中的代码一样。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句