AngularJS -- 将ngModel绑定到存储在属性中的对象

AngularJS -- Bind ngModel to an object stored in a property

本文关键字:属性 对象 存储 ngModel 绑定 AngularJS      更新时间:2023-09-26

我正在尝试以编程方式填充输入列表。

我有类似的东西

<div ng-repeat="field in fields">
<input ng-model="field.Binding" />
</div>
var Query = {
    Keywords: "Foo",
    Title: "Bar"
}
var Fields = [{
    Name: "Keywords",
    Binding: Query.Keywords
}, {
    Name: "Title",
    Binding: Query.Title
}];
var myApp = angular.module('myApp', []);
function MyCtrl($scope) {
    $scope.fields = Fields;
    $scope.query = Query;
}

非工作小提琴@http://jsfiddle.net/VSph2/52/当我启动视图时,字符串被复制,但这两个值不会相互更新。

基本上,我想绑定到通过引用或名称指定的对象,例如"Query.Keywords",并让范围在运行时对此进行评估 - 但我运气不佳。

正如你在小提琴中看到的,我的价值观不会保持同步。

感谢扎克引导我走向正确的方向。

无论如何,如果您使用字符串值进行绑定,例如

字段 { 绑定:"foo"}

然后,您可以绑定到 data[Field.Binding],这将正常工作。我的第一个示例不起作用,因为它绑定到字符串值,而不是数据的属性本身。

工作小提琴@http://jsfiddle.net/VSph2/57/

function cQuery() {
    this.Keywords= "Foo";
    this.Title = "Bar";
}
var Query = new cQuery();
var Fields = [{
    Name: "Keyword Search",
    Binding: "Keywords"
}, {
    Name: "Title Search",
    Binding: "Title"
}];

var myApp = angular.module('myApp', []);
function MyCtrl($scope) {
    $scope.blah = Object.keys(Query);
    $scope.fields = Fields;
    $scope.query = Query;
}
<div ng-controller="MyCtrl">
    <div ng-repeat="field in fields">{{field.Name}}
        <input type="text" ng-model="query[field.Binding]" type="text" class="form-control" id="{{field.Id}}" /> {{field.Binding}}
    </div>Elsewhere...
    <input ng-model="query.Keywords"  type="text"/> {{query.Keywords}}
</div>

我编辑了你查看数据的方式。希望这有所帮助。

http://jsfiddle.net/VSph2/42/

 Removed query, attached input directly to fields.