Reputation: 1096
I am trying to create a tags input-field, with auto-complete. Here is the Angular code:
var app = angular.module('plunker', ['ngTagsInput']);
app.controller('MainCtrl', function($scope, $http) {
$scope.loadTags = function(query) {
return $http.get(Routing.generate('my_route_to_json_data'));
}
});
HTML code:
<body ng-app="plunker" ng-controller="MainCtrl">
<tags-input ng-model="tags" add-on-paste="true" display-property="categoryname" placeholder="Add a Tag">
<auto-complete max-results-to-show="4" min-length="0" source="loadTags($query)"></auto-complete>
</tags-input>
<p>Model: {{tags}}</p>
</body>
The $http.get(Routing.generate('my_route_to_json_data'));
returns tags.json
:
[{"categoryname":"wifi"},{"categoryname":"cable"},{"categoryname":"tv"},{"categoryname":"geyser"},{"categoryname":"fridge"},{"categoryname":"sofa"},{"categoryname":"lift"},{"categoryname":"gas stove"},{"categoryname":"washing machine"}]
This works perfeclty. When I enter some input in the field, the suggestions appear in the dropdown.
Problem: Now I want the suggestions being displayed to be filtered, based on user input.
For that I changed my Angular code to this:
var app = angular.module('plunker', ['ngTagsInput']);
app.controller('MainCtrl', function($scope, tags) {
$scope.loadTags = function(query) {
return tags.load();
};
});
app.service('tags', function($q, $http, $filter) {
var tags = $http.get(Routing.generate('my_route_to_json_data'));
this.load = function(query) {
var deferred = $q.defer();
deferred.resolve( $filter('filter')($scope.tags, query));
return deferred.promise;
};
});
Doesn't work :(
Any and all help is appreciated.
Upvotes: 1
Views: 79
Reputation: 12025
I would change the service to something like:
app.service('tags', function($q, $http, $filter) {
this.load = function(query) {
return $http.get(Routing.generate('my_route_to_json_data')).then(
function(result) {
return $filter('filter')(result.data, query)
}
)
};
});
The service now return a chained promises and the resolve function is dealing with the filter.
You can cache the results, and return a promise (Using the $q
service) that relove the array of tags previously returned from the server.
Don't know if the filter itself is working - But now it will have list of items to filter and not undefined
value ($scope.tags
).
Upvotes: 2