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

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

问题描述

我是角度输入修改指令的作者。



此指令用于跟踪模型的值,并允许检查值是否已修改,并且还提供了 reset()函数现在,模型的初始值被存储在 ngModelController.masterValue 属性中并提供 ngModelController.reset()函数。请参阅执行
$ b 我使用以下语句: eval('$ scope。'+ modelPath +'= modelCtrl.masterValue;'); 为了恢复到它的初始状态。 modelPath 这里实际上是 ng-model 属性的值。这是我开发的一种方式,我不喜欢这种方法,因为 ng-model 值可能很复杂,嵌套的作用域也会打破这个功能。



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

解决方案

迄今为止找到的最佳解决方案是使用 $ parse 服务来分析<$ c中的Angular表达式$ c> ng-model 属性并为其检索setter函数。然后我们可以通过调用这个setter函数来改变模型的值。

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

这比 eval()






如果您有更好的主意,请提供其他答案或仅对此评论。谢谢!


I'm an author of angular-input-modified directive.

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.

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

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.

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

解决方案

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.

Example:

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

This works much more reliably than eval().


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

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

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