在 Angular.js 中以编程方式设置模型值 [英] Set model value programmatically in Angular.js

查看:22
本文介绍了在 Angular.js 中以编程方式设置模型值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 angular-input-modified 指令的作者.

该指令用于跟踪模型的值并允许检查该值是否被修改,并且还提供了reset()函数将值更改回初始状态.

This directive is used to track model's value and allows to check whether the value was modified and also provides reset() function to change value back to the initial state.

现在,模型的初始值存储在 ngModelController.masterValue 属性中,并且提供了 ngModelController.reset() 函数.请参阅实施.

Right now, model's initial value is stored in the ngModelController.masterValue property and ngModelController.reset() function is provided. Please see the implementation.

我正在使用以下语句:eval('$scope.' + modelPath + ' = modelCtrl.masterValue;'); 以便将值恢复到其初始状态.modelPath 这里其实就是一个ng-model属性的值.这是开发的一种方式,我不喜欢这种方法,因为 ng-model 值可能是一个复杂的值,而且嵌套范围会破坏此功能.

I'm using the following statement: eval('$scope.' + modelPath + ' = modelCtrl.masterValue;'); in order to revert value back to it's initial state. modelPath here is actually a value of ng-model attribute. This was developed a way back and I don't like this approach, cause ng-model value can be a complex one and also nested scopes will break this functionality.

重构此语句的最佳方法是什么?如何直接通过 ngModel 控制器的接口更新模型的值?

What is the best way to refactor this statement? How do I update model's value directly through the ngModel controller's interface?

推荐答案

目前我发现的最佳解决方案是使用 $parse 服务以解析 ng-model 属性中的 Angular 表达式并为其检索 setter 函数.然后我们可以通过使用新值调用这个 setter 函数来更改模型的值.

The best solution I've found so far is to use the $parse service in order to parse the Angular's expression in the ng-model attribute and retrieve the setter function for it. Then we can change the model's value by calling this setter function with a new value.

function reset () {
  var modelValueSetter = $parse(attrs.ngModel).assign;
  modelValueSetter($scope, 'Some new value');
}

这比 eval() 更可靠.

如果您有更好的想法,请提供另一个答案或仅对此发表评论.谢谢!

If you have a better idea please provide another answer or just comment this one. Thank you!

这篇关于在 Angular.js 中以编程方式设置模型值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆