gpt4 book ai didi

javascript - 与 ng-change 和 select 交互——改变数据源触发改变

转载 作者:行者123 更新时间:2023-11-29 21:41:40 25 4
gpt4 key购买 nike

请检查这个插件:http://plnkr.co/edit/ke4Cjg3gnf2pWUKW1f2b?p=preview .

var app = angular.module('app', []);

app.controller('controller', ['$scope', '$timeout', function($scope, $timeout) {
$scope.items = [
{name:'candy'},
{name:'chocolate'}
];
$scope.choice = null;

$scope.test = function() {
console.log( 'fired' );
}

$timeout( function(){
$scope.choice = $scope.items[0];
}, 2000);

$timeout( function(){
$scope.items = [
{name:'hershey'},
{name:'mint'}
];
}, 5000);
}]);

    <select 
ng-model="choice"
ng-options="item as item.name for item in items"
ng-change="test()">
</select>

我有一个使用 ng-options 和 ng-change 事件的选择框。 Ng-change 文档说明如下:

The ngChange expression is only evaluated when a change in the input value causes a new value to be committed to the model.

It will not be evaluated:

  • if the value returned from the $parsers transformation pipeline has not changed
  • if the input has continued to be invalid since the model will stay null
  • if the model is changed programmatically and not by a change to the input value

显然,如果我以编程方式将模型设置为等于某个值,则什么也不会发生,但我发现当我动态更改 ng-options 的源时,ng-change 正在触发 unless ng-model在结果更改时等于 null 值。

这是错误还是有意为之?如果有意,如何在不先将 ng-model 设置为 null 的情况下更改 ng-options 的来源而不导致 ng-change 触发?如果没有,我会去报告这个奇怪的行为。

谢谢!

最佳答案

这是发生了什么:

  1. 您从下拉列表中选择一个值(例如糖果)。
  2. 超时后。在 $scope.items 中创建了一个新数组。此时,angularjs 将使用一组新的项目重新填充 HTML 下拉框(选择)。这将导致 DOM 中的元素将其值从先前选择的元素(例如糖果)更改为 null。
  3. 此更改会导致计算 ng-change 表达式。

这是有效的,因为 a) 有一个变化(从 candy 到 null)并且 b) 变化不是通过对模型(而是对底层 DOM 元素)的编程更改完成的。

解决 if 的方法因您要执行的操作而异。在您提供的示例中,基础值将始终更改,因为新选项会替换所有旧选项。但请考虑以下示例,我选择删除巧克力并添加两个新值(保留糖果选项):

$timeout( function(){
delete $scope.items[1]; // removes item choclate from the list.

// Add new items
$scope.items[1] = {name : 'hershey' };
$scope.items[2] = {name : 'mint' };

}, 5000);

在这种情况下,如果用户选择“糖果”,则 ng-change 不会触发,因为所选选项保持不变。另一方面,如果用户选择“chocolate”,更改将触发(因为值从“chocolate”变为 null)。因此,您可能需要考虑以下选项:

  1. 仅向下拉列表添加项目。
  2. 如果需要删除所选选项,则将值设置为 null(这不会触发,因为您是以编程方式设置模型)。
  3. 替换整个数组,使 ng-change 触发,但在 ng-change 调用的函数内执行检查,以处理模型未触发的情况。

关于javascript - 与 ng-change 和 select 交互——改变数据源触发改变,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32616234/

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