Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 1000
Scott Christopherson Avatar asked Mar 23 '13 17:03

Scott Christopherson


1 Answers

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.

like image 174
Martin Avatar answered Oct 24 '22 17:10

Martin