我正在使用ng-init在输入字段中获取一些默认值。它工作正常。但是当我在输入字段中添加ng-autocomplete时,默认值不再显示在输入字段中。
的index.html
<!DOCTYPE html>
<html ng-app=testApp>
<head>
<link rel="stylesheet" href="style.css">
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?libraries=places&sensor=false"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.js"></script>
<script src="script.js"></script>
<script src="ngAutocomplete.js"></script>
</head>
<body>
<div ng-controller="searchCtrl" ng-init="roomsInit('london')">
<input type="text" ng-autocomplete ng-model="searchLocation" class="form-control input-lg" options="locationFilter">
</div>
</body>
</html>
的script.js
app = angular.module("testApp", ['ngAutocomplete']);
app.controller('searchCtrl', function ($scope, $http) {
$scope.locationFilter = {
country: 'uk',
types: '(cities)'
}; $scope.details2 = '';
$scope.roomsInit = function (location) {
$scope.searchLocation = location;
//below code is not relevant to this case
$http({
url: "/search.json",
method: "GET",
params: {location: $scope.searchLocation,
q: {
daily_price_gteq: $scope.min_price,
daily_price_lteq: $scope.max_price,
room_type_eq_any: [$scope.private, $scope.entire, $scope.shared]
}
},
paramSerializer: '$httpParamSerializerJQLike'
}).success(function (response) {
$scope.rooms = response.rooms;
});
};
});
如果我删除ng-autocomplete,它可以正常工作。有人可以看看 Here is the plunker
答案 0 :(得分:1)
您使用的指令不支持ng-model,并且要求您将模型传递给ng-autocomplete:
<input type="text" ng-autocomplete="result" details="details" class="form-control input-lg" options="locationFilter">
当您在框中键入时,这将运行自动完成。
我相信你所遵循的指令就是这个:https://github.com/wpalahnuk/ngAutocomplete/blob/master/src/ngAutocomplete.js
<强>更新强>
您使用的指令有一个监视器,它在第一次运行后清除该值:
scope.$watch(scope.watchOptions, function () {
initOpts()
newAutocomplete()
element[0].value = ''; // <-- This resets the value
scope.ngAutocomplete = element.val();
}, true);
如果您不关心修改指令,请将其更改为:
scope.$watch(scope.watchOptions, function (newValue, oldValue) {
if (newValue !== oldValue) {
initOpts()
newAutocomplete()
element[0].value = '';
scope.ngAutocomplete = element.val();
}
}, true);
除非您更改选项/ locationFilter
。