ng-list input not updating when adding items to array

All we need is an easy explanation of the problem, so here it is.

I’m running into a strange issue where an input using ng-list isn’t updating when adding items to the model. I’ve created a fiddle to better illustrate the issue:

// Doesn't update ng-list input

// Does update ng-list input
var tags = angular.copy($scope.tags);
$scope.tags = tags;

This doesn’t seem like expected behavior, especially since $scope.tags is being properly updated as illustrated by the <pre> tag in the jsFiddle above.

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

Ok, so this was interesting. I dug into the unminified AngularJS source code for the ngList directive.

It seems as the first example doesn’t trigger the formatter function, which is the function that splits the array values into a comma separated string that is displayed in the input field.

Further investigation shows that the error lies in the ngModel directive’s controller. Formatters are only invoked if the value is strictly not equal to the previous value, but since it is the same array instance in your first example, that statement evaluates to false, and hence the text field isn’t updated. See the source code.

$scope.$watch(function ngModelWatch() {
    var value = ngModelGet($scope);

    // $modelValue and value is the same array instance in your first example
    if (ctrl.$modelValue !== value) {
        // ...

In your second example you create a new array instance each time and hence the formatters are run.

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply