Estoy usando la directiva ngTagInput para sugerencias automáticas. Lo que quiero es borrar la sugerencia automática después de hacer clic en la sugerencia. Aunque se borra en la primera llamada de función, pero no en la segunda. Se agrega como etiqueta en la segunda llamada de función. y quiero eliminar eso
En HTML,
<tags-input ng-model="autoSongs"
key-property="_id"
display-property="name"
add-from-autocomplete-only="true"
replace-spaces-with-dashes="false"
on-tag-adding="songAdded($tag)"
on-tag-added="emptyScope()"
template="tag-template"
placeholder="type here to search for album..."
on-tag-removed="songRemoved($tag)">
<auto-complete source="loadSongs($query)"
min-length="2"
debounce-delay="5"
max-results-to-show="10"
template="autocomplete-template"></auto-complete>
</tags-input>
De esta manera en el controlador,
$scope.loadSongs = function(query) {
var autoFilter = 'name=' + query;
return songService.autoSuggest(autoFilter, function(error, data) {
if (error) {
toastr.error(error.message, 'Error');
return false;
}
return data;
});
};
$scope.songAdded = function(query) {
if ($scope.pushArray.checkbox.length === 0) {
toastr.error('Select record to assign album.', 'Error');
return false;
}
var songId = query._id,
songName = query.name;
videoService.assignSong(songId, $scope.pushArray.checkbox, function(err, resonse) {
if (err) {
toastr.error(err.message, 'Error');
} else {
$scope.emptyScope();
toastr.success('\'' + songName + '\' has been assigned to ' + resonse + ' records', 'Success');
$scope.pageChanged();
}
});
return true;
};
$scope.emptyScope = function() {
$scope.autoSongs = null;
};
Su valor no se borra en el segundo intento. ¿Puedo usar la sugerencia automática con devoluciones de llamada por separado?
3 respuestas
Si la consola registra el valor de $scope.autoSongs
, descubrirá que de hecho es un array
.
Entonces, su función que vacía el valor tiene que ser así:
$scope.emptyScope = function() {
//$scope.autoSongs = null;
$scope.autoSongs = [];
};
PD: lea también esto, así que responda SO sobre el vaciado de una matriz.
Esta Plunker parece funcionar bien.
on-tag-adding="songAdded($tag)"
Parece ser el único evento que necesita activar.
Intenté usar $ timeout para diferir la función emptyScope()
; compruebe si el resultado es el que desea:
var app = angular.module('myApp', ['ngTagsInput']);
app.controller('MainCtrl', function($scope, $timeout, songService) {
$scope.autoSongs = [];
$scope.loadSongs = function(query) {
console.log("loadSongs: " + query);
return songService.autoSuggest(query);
};
$scope.songAdded = function(query) {
console.log("songAdded: " + query);
var songId = query._id,
songName = query.name;
$timeout(function() {
console.log("$timeout: ");
$scope.emptyScope();
});
return true;
};
$scope.emptyScope = function() {
console.log("emptyScope: ");
$scope.autoSongs = [];
};
});
app.factory('songService', function() {
var autoSuggest = function(autoFilter) {
console.log("autoSuggest: " + autoFilter);
if (autoFilter == "i")
return [{name: 'India',_id: 1}, {name: 'Indonesia',_id: 2},{name: 'Italy',_id: 3} ];
else if (autoFilter == "u")
return [{name: 'United Arab',_id: 4}, {name: 'Uganda',_id: 5},{name: 'USA',_id: 6} ];
else
return [{name: 'Germany',_id: 7}, {name: 'Greece',_id: 8},{name: 'Chezk',_id: 9} ];
}
return {autoSuggest:autoSuggest};
});
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>
document.write('<base href="' + document.location + '" />');
</script>
<!--link rel="stylesheet" href="style.css" /-->
<link rel="stylesheet" href="http://mbenford.github.io/ngTagsInput/css/ng-tags-input.min.css" />
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.2/angular.min.js"></script>
<script src="http://mbenford.github.io/ngTagsInput/js/ng-tags-input.min.js"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
<tags-input ng-model="autoSongs" key-property="_id" display-property="name" add-from-autocomplete-only="true" replace-spaces-with-dashes="false" on-tag-adding="songAdded($tag)" on-tag-added="emptyScope()" placeholder="type here to search for album..."
on-tag-removed="songRemoved($tag)">
<auto-complete source="loadSongs($query)" min-length="1" debounce-delay="5" max-results-to-show="10"></auto-complete>
</tags-input>
<p>Model: {{autoSongs}}</p>
<p>Search with I or U or else</p>
</body>
</html>
Y también el Plunker actualizado: http://plnkr.co/edit/7nt3toEclsP5HXL7RadP?p=preview
Preguntas relacionadas
Nuevas preguntas
javascript
Para preguntas relacionadas con la programación en ECMAScript (JavaScript / JS) y sus diversos dialectos / implementaciones (excluyendo ActionScript). Esta etiqueta rara vez se usa sola, pero a menudo se asocia con las etiquetas [node.js], [json] y [html].