当从下拉列表中选择项目时,在将选中的项目插入到ng-model之前,如何进行一些逻辑处理

How to proceed some logic when item selected from dropdownlist and before the selected item inserted to ng-model?

本文关键字:项目 ng-model 何进行 之前 处理 选择 下拉列表 插入      更新时间:2023-09-26

我有这个下拉列表指令。

<select class="form-control"
        ng-model="editor.frequency"
        ng-options="item as item.Name for item in editor.frequencies"
        ng-change="editor.checkSiteFrequencyInspections(editor.frequency, {{editor.frequency}});">
</select>

当用户单击下拉列表中的某个选项时,所选项目被插入到名为frequency的属性中。

我需要在用户从下拉列表中选择项目之后进行一些逻辑,然后将其插入到名为frequency的属性中(只有在逻辑进行之后,frequency才能获得选中的项目)。

知道如何实现它吗?

要在模型更改之前执行函数,使用指令将$parser添加到ngModelController:

angular.module("myApp").directive("preChange", function () {
    return {
        require: "ngModel",
        link: function(scope,elem,attrs,ngModelCtrl) {
             console.log("Pre instantiated")
             ngModelCtrl.$parsers.push(function(value) {
                  scope.$eval(attrs.preChange, {$value: value});
                  return value;
             })
        }
    }
});

上面的指令将$parser添加到执行由pre-change属性定义的AngularJS表达式的ngModelController中。新值暴露为$value

用法:

<select class="form-control"
        ng-model="editor.frequency"
        ng-options="item as item.name for item in editor.frequencies"
        ng-change="change(editor.frequency.name)"
        pre-change="pre($value.name)">
</select>

From the Docs:

$parsers

当控件从DOM读取值时,作为管道执行的函数数组。函数按数组顺序调用,每个函数将其返回值传递给下一个函数。最后一个返回值被转发到$validators集合。

——AngularJS ngModelController API Reference——$parsers

嗯,我猜ng-change$watch(通常用于检测更改)对您没有帮助,因为它们是在更改发生后调用/执行的。

这个简单的hack怎么样?

  1. 在你的html,而不是使用editor.frequencyng-model,你可以使用一个临时的$scope变量(即:$scope.editor.temp)

    <select class="form-control"
        ng-model="editor.temp"
        ng-options="item as item.Name for item in editor.frequencies">
    </select>
    
  2. ,在您的controller中,您可以查看$scope.editor.temp,一旦你发现任何变化,你在这里执行预先分配频率的逻辑,然后执行可以将值赋给实际的$scope.editor.frequency

    $scope.$watch('editor.temp', function(newValue, oldValue) {
        //perform your pre-frequency-is-assigned logic here
        $scope.editor.frequency = newValue;
    });