NoviceDeveloper NoviceDeveloper - 1 year ago 147
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"> {{}}</span>

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

Answer Source

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]];
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download