I have an <input ng-model='list' ng-list>
, and I want to make sure that no duplicates appear in this text field—I want to automatically remove them if the list contains duplicates.
I put a $scope.$watch('list', function(listValues) {
in the controller, and try to remove any duplicates from listValues
, but have problems. From within the watch function, if I set listValues = _.unique(listValues)
, $scope.list
's value never changes. If I try $scope.list = _.unique(listValues)
, I get an error about the digest cycle already running.
How can I watch for a scope variable to change, and when it does, perform an operation to change that new value?
Here's an example of it not working: http://plnkr.co/edit/b0bAuP1aXPg3HryxCD9k?p=preview
I thought this would be simple. Is there some other approach that I should be using?
ng-change is probably a better approach in this case. In particular, this attribute of ng-change
:
if the model is changed programmatically and not by a change to the input value
If you place your de-dupe in a function and then use ng-change
to call it, I think you will get the results you are after.