gpt4 book ai didi

javascript - 将项目添加到数组时 ng-list 输入不更新

转载 作者:可可西里 更新时间:2023-11-01 02:36:28 26 4
gpt4 key购买 nike

我遇到了一个奇怪的问题,即在向模型添加项目时使用 ng-list 的输入没有更新。我创建了一个 fiddle 来更好地说明这个问题: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;

这看起来不像是预期的行为,尤其是因为 $scope.tags正在正确更新,如 <pre> 所示上面 jsFiddle 中的标记。

最佳答案

好的,所以这很有趣。我为 ngList directive 挖掘了未压缩的 AngularJS 源代码。 .

第一个示例似乎没有触发格式化程序函数,该函数将数组值拆分为逗号分隔的字符串,并显示在输入字段中。

进一步调查表明,错误在于 ngModel 指令的 controller .仅当该值严格不等于前一个值时才会调用格式化程序,但由于它在您的第一个示例中是相同的数组实例,因此该语句的计算结果为 false,因此不会更新文本字段。 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) {
// ...
}
});

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

关于javascript - 将项目添加到数组时 ng-list 输入不更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15590140/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com