Search code examples
javascriptangularjsng-tags-input

Ng-Tag-Input Directive not clearing value


I am using ngTagInput directive for auto-suggestion. What I want is clear the auto-suggestion after suggestion is clicked. Though its clearing on first call of function but not on second. It is adding as tag on second function call. and I want to remove that.

On 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>

This way on controller,

$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;
    };

Its not clearing value on second attempt. Can I use auto-suggestion with callbacks separately?

plunker


Solution

  • If you console log the value of $scope.autoSongs you will find out that it is indeed an array.
    So your function that empties the value has to be like this:

    $scope.emptyScope = function() {
        //$scope.autoSongs = null;
    
        $scope.autoSongs = [];
    };
    

    working plunker

    PS: please read also this SO answer about emptying an array.