NoviceDeveloper NoviceDeveloper - 1 month ago 16
AngularJS Question

md-chip can add duplicates if model already contains item

I have the following code:

<md-chips ng-model="myModel" md-autocomplete-snap="true" md-require-match="autocompleteDemoRequireMatch">
<md-autocomplete md-selected-item="selected" md-search-text="searchText" md-items="item in myItems| filter:{name: searchText}" md-item-text="item" placeholder="Search ...">
<span md-highlight-text="searchText"> {{item.name}}</span>
</md-autocomplete>
<md-chip-template>
<span>
<strong>{{$chip.name}}</strong>
</span>
</md-chip-template>
</md-chips>


My model myModel contents are as follows:

[{"id":"1","name":"Judy Foster"}]


and my md-items like so:

[{"id":"1","name":"Judy Foster"}, {"id":"2","name":"Rudy Foster"}, {"id":"3","name":"Moody Foster"}]


What happens is if my myModel has nothing .. it works fine, as it does not allow me to enter duplicates.

When myModel already contains an item that also exist in myItems it allows a duplicate.

Anyone any idea how to prevent the duplication from happening?

Here is jsfiddle https://jsfiddle.net/9xyrktwL/

Answer

This happens because your model object and the first item of your items list are not the same, even if it has the same attributes, they are different objects in memory, so try to rewrite your controller to point to the same object, like that:

var app = angular.module('app', ['ngMaterial']);

app.controller('ctrl', ['$scope', '$filter', function($scope, $filter) {


    $scope.myItems = [{"id":"1","name":"Judy Foster"}, {"id":"2","name":"Rudy Foster"}, {"id":"3","name":"Moody Foster"}];
    $scope.myModel = [$scope.myItems[0]];
}]);
Comments