Scott Christopherson
Scott Christopherson

Reputation: 590

ng-list input not updating when adding items to array

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: http://jsfiddle.net/rtZY3/

// Doesn't update ng-list input
$scope.tags.push(tag);

// Does update ng-list input
var tags = angular.copy($scope.tags);
tags.push(tag);
$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.

Upvotes: 10

Views: 1692

Answers (1)

Martin
Martin

Reputation: 8866

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.

Upvotes: 15

Related Questions