当从下拉列表中选择项目时,在将选中的项目插入到ng-model之前,如何进行一些逻辑处理
How to proceed some logic when item selected from dropdownlist and before the selected item inserted to ng-model?
我有这个下拉列表指令。
<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怎么样?
-
在你的
html
,而不是使用editor.frequency
在ng-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>
-
,在您的
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; });
相关文章:
- 从 Javascript 中设置 ng-model name
- Toggle Switch在包含ng model和ng repeat之后不进行切换
- 在Angularjs中,我如何使用ng repeat、ng model和ng click来动态更改内容
- 当与之关联的 ng-model 为 false 时,Angularjs 复选框值不会取消选中
- ng-model 绑定到选择标签生成的空默认值
- 对象不能在angularjs ng-model中访问
- 为什么 HTML 中的 Value 属性在与 AngularJS 中的 ng-model 一起使用时不起作用
- ng-repeat不绑定ng-model对象数组
- AngularJS:ng-model 绑定在使用 jQuery 更改时不会更新
- 选择/选项 ng-model 未绑定 ng-selected
- Angular ng-model 将数据作为数组发送到 rails-api
- 为什么 AngularJS 在使用 ng-model 时不会在文本框上设置长度属性
- AngularJS:Ng:init-如何分配Ng:model
- 在指令中使用 ng-model 和 ng-repeat
- 使用 angularjs 访问控制器中的 ng-model 数据
- 如何在 Angularjs 中为 ng-model 增加价值
- 如何在 AngularJS 中将 ng-model 值检索到控制器
- 从角度“ng-model”选择元素中选择第一个选项,带有一个按钮
- 使用 ID 更新文本区域值,而不是在 AngularJs 中使用 ng-model
- 当从下拉列表中选择项目时,在将选中的项目插入到ng-model之前,如何进行一些逻辑处理