在Angular.js的ngModel中使用表达式 [英] Using expressions in ngModel in Angular.js
问题描述
在控制器内部提供代码:
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函数. 可以在此小品
That will return a getter-setter function that handles this for you. see it in action in this plunk
这篇关于在Angular.js的ngModel中使用表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!