在 Angular.js 中使用 ngModel 中的表达式 [英] Using expressions in ngModel in Angular.js

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

问题描述

在我的控制器中提供代码:

Giving the code inside of my controller:

$scope.entity = {
  firstName: 'Jack',
  lastName: 'Bauer',
  location: {
    city: 'New York'
  }
};
$scope.path = 'location.city';

如何将ngModel动态绑定到path指定的entity的属性上?

How do I dynamically bind ngModel to the property of the entity specified by path?

我尝试过类似的方法,但无济于事:

I've tried something like this, but to no avail:

<input ng-model="'entity.' + path">

推荐答案

Slava,我不太确定这是否是一个好主意.但无论如何,您需要通过将此属性添加到您的输入 ng-model-options="{ getterSetter: true } 来使您的模型 getterSetter 知道.然后你需要在你的控制器中使用一个函数来构建一个 getterSetter.

Slava, I'm not too sure if this is a good idea to begin with. But anyhow, You need to make your model getterSetter aware by adding this property to your input ng-model-options="{ getterSetter: true }. Then you need a function in your controller that builds a getterSetter out of a sting.

<input type="text" ng-model="propertify('entity.' + path)" ng-model-options="{ getterSetter: true }">

这就是生成的模板的外观.

That's how the resulting template would look.

幸运的是 angular 有一个 $parse 服务,这让这件事变得容易多了.所以像这样的东西需要在你的控制器中,或者在注入的服务中更好.

Luckily angular has an $parse service that makes this a lot easier. so something like this would need to be in your controller, or even better in a injected service.

  $scope.propertify = function (string) {
      var p = $parse(string);
      var s = p.assign;
      return function(newVal) {
          if (newVal) {
              s($scope,newVal);
          }
          return p($scope);
      } ;
  };

这将返回一个 getter-setter 函数来为你处理这个问题.在 this plunk

That will return a getter-setter function that handles this for you. see it in action in this plunk

这篇关于在 Angular.js 中使用 ngModel 中的表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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