出于澄清目的重新表述问题。
Plunkr
查看:
<input type="text" ng-model="form['data']['sampleData']">
<input type="text" ng-model="form[bindingPrefix][bindingSuffix]">
<input type="text" ng-model="form[bindingValue]">
Controller :
$scope.form = {
data: {
sampleData: '123'
}
};
$scope.bindingValue = 'data.sampleData';
$scope.bindingPrefix = 'data';
$scope.bindingSuffix = 'sampleData';
想要的效果:
我期望 form[bindingValue]
产生 form[bindingPrefix][bindingSuffix]
的效果没有故意分开bindingValue
至bindingPrefix
和bindingSuffix
因为绑定(bind)值可以是动态值,例如 data.sampleData.childData
, data.sampleData.childData.childChildData
在用于 ng-repeat 模型的数组中。
P/S:绑定(bind)值是从服务器端传递的东西,我无法控制它。
================================================== =========================== 可能可以从这里的这个笨蛋那里得到。理想情况下,不应修改 View 。 Click here
最佳答案
即使路径可以是可变长度的,我们也可以将问题减少到仅使用一个变量的路径。只要您不破坏数据对象的结构,这应该可以工作(或者如果您这样做,请记住再次运行此准备代码)。
所以我们有数据
$scope.form = {
data: {
sampleData: '123'//This could be even deeper in the object, can't know for sure
}
};
但我们需要保持 sampleData
和包含对象之间的链接的唯一变量名称是最后一个。 “样本数据”。如果我们只获取对 data
对象和“sampleData”属性名称的引用,则可以丢弃所有其他属性名称。
在 Controller 中:
//Get the path from the server, split it to create an array of property names
var path = 'data.sampleData'.split('.');
//We'll start changing these soon
var prevValue = $scope.form, nextValue;
for(var i = 0; i < path.length - 1; i++){//Note that we are not looping all the way through (-1)!
//Get all the properties one by one
nextValue = prevValue[path[i]];
if(nextValue == undefined){
//This is an error, the data didn't conain the property that it was supposed to.
//It's up to you how to handle this. Doing the following will add the missing properties and keep things working.
nextValue = prevValue[path[i]] = {};
}
//The prevValue will first be $scope.form, then form.data
prevValue = nextValue;
}
//$scope.bindingContainer is a reference to $scope.form.data object
$scope.bindingContainer = prevValue;
//$scope.bindingValue is the last property name, "sampleData"
$scope.bindingValue = path[path.length-1];
在模板中:
<input type="text" ng-model="bindingContainer[bindingValue]">
一切都应该正常工作(同样,只要您不更改 $scope.form.data = SomethingElse
)。
当然,我们有点作弊,因为现在模板根本不引用原始的 $scope.form
对象。但这并不重要,因为它引用了 data 对象及其属性“sampleData”,因此只要 $scope.form
引用 < strong>相同 data
对象,我们已经拥有了我们需要的一切。
关于javascript - Angular 绑定(bind)为对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37014974/