10

I've taken up Angular recently as a learning exercise.

I'd like to pass a method to ng-model or an expression which might evaluate to one.

In this fiddle http://jsfiddle.net/C4aGk/ you'll see that I've hard coded the field as ng-model="record.inner[0].text" and it works, now the thing is, i'd like to replace the hard-coded zero with something that is returned at run-time, selected by a criterion say id = 1.

My HTML code:

<div ng-controller="MainController" ng-app>
    <div ng-repeat="record in records">
        <input ng-model="record.inner[0].text"> <span>{{record.outer}}</span>
        <div ng-repeat="nested in record.inner">{{nested.id}} - {{nested.text}}</div>
        <hr />
    </div>
</div>
<br/>

and the corresponding js:

function MainController($scope) {
    $scope.records = [{
        outer: "Hello",
        inner: [{
            id: 1,
            text: "Angular"
        }, {
            id: 2,
            text: "jQuery"
        }]
    }, {
        outer: "World",
        inner: [{
            id: 1,
            text: "Node.js"
        }, {
            id: 2,
            text: "Underscore.js"
        }]
    }];

    $scope.getText = function (record) {
        var index = 0;
        for (nested in record.inner) {
            if (nested.id === 1) {
                return "record.inner[" + index + "].text";
            }
            index++;
        }
    };

I've tried placing ng-model="getText(record)" as per https://groups.google.com/forum/#!topic/angular/Pef6LY2rT7g with no success, and another search turned up this https://github.com/angular/angular.js/pull/1328 which is equally unhelpful to me.

Any help will be highly appreciated.

4

1 回答 1

11

您传递给 ng-model 的任何内容都会被评估为针对范围的角度表达式。这意味着它record.inner[0].text被评估为$scope.record.inner[0].text然后使用该表达式的结果。当您使用时getText(record),角度评估$scope.getText(record)并且 ng-model 可以访问此评估的结果。请记住,ng-model 不会评估此函数调用的结果。

您的问题是您将结果作为角度表达式字符串返回,但从不对其进行评估,因此 ng-model 得到了一个它无法使用的字符串。有很多方法可以重新设计代码来处理这个问题,但简单(可能不是最好的)方法是使用类似 ng-init 的方法来获取函数调用的结果,然后将结果插入到 ng-模型。请参阅此小提琴以获取快速示例http://jsfiddle.net/z5z9s/

于 2013-07-22T17:31:05.143 回答