4

I am trying to populate programatically a list of inputs.

I have something like

<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;
}

Non-working fiddle @ http://jsfiddle.net/VSph2/52/ The string is copied when I start my view, but the two values do not update eachother.

Basicallyk I'd like to bind to an object specified by reference or by name e.g "Query.Keywords" and have the scope evaluate this at runtime -- but I am not having much luck.

As you can see in the fiddle, my values do not stay synchronized.

4

2 回答 2

3

Thanks Zack for steering me in the right direction.

At any rate, if you use a string value for the binding e.g

Field { Binding: "Foo"}

You can then bind to data[Field.Binding] and this will work just fine. My first example was not working because it was binding to the string value, not the property itself of my data.

Working fiddle @ 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>
于 2013-10-29T12:49:58.513 回答
1

I edited the way you looked at the data. Hopefully this helps.

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

 Removed query, attached input directly to fields.
于 2013-10-28T21:15:16.683 回答