向项目添加项目时,ng-list输入未更新

Sco*_*son 10 javascript angularjs

我遇到了一个奇怪的问题,即在向模型添加项目时,使用ng-list的输入不会更新.我创造了一个小提琴来更好地说明这个问题: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;
Run Code Online (Sandbox Code Playgroud)

这似乎不是预期的行为,特别是因为正如上面的jsFiddle中$scope.tags<pre>标签所示正确更新.

Mar*_*tin 15

好的,所以这很有趣.我挖掘了ngList指令的未经授权的AngularJS源代码.

似乎第一个示例不会触发formatter函数,该函数将数组值拆分为输入字段中显示的逗号分隔字符串.

进一步调查显示错误在于ngModel指令的控制器.仅当值严格不等于前一个值时才调用格式化程序,但由于它与第一个示例中的数组实例相同,因此该语句的计算结果为false,因此不会更新文本字段.查看源代码.

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

    // $modelValue and value is the same array instance in your first example
    if (ctrl.$modelValue !== value) {
        // ...
    }
});
Run Code Online (Sandbox Code Playgroud)

在第二个示例中,每次都创建一个新的数组实例,因此运行格式化程序.