【问题标题】:AngularJS: How do I bind data in nested ng-repeats?AngularJS:如何在嵌套的 ng-repeats 中绑定数据?
【发布时间】:2014-03-15 22:47:32
【问题描述】:

我使用 Angular 从$http 调用返回了一个非常嵌套的 JSON 对象。在我的模板中,我必须嵌套几个 ng-repeats 才能呈现数据。我似乎无法弄清楚如何在文本输入上使用 ng-model 绑定数据。

我读到this question 说返回对象不是$scope 中的自动数据,您必须遍历数据并实例化结构。我也尝试过,结果相同。

        // Seemingly unnecessary code
        angular.forEach(Object.keys($scope.sources), function(sourcename){
            $scope.sourceData[sourcename] = {};
            angular.forEach(Object.keys($scope.sources[sourcename]), function(key){
                $scope.sourceData[sourcename][key] = $scope.sources[sourcename][key];
        });

这是一个展示我尝试的小提琴:

http://jsfiddle.net/c7z9C/2/

我只想将值填充到字段中并绑定到模型。提前感谢您的任何建议。

【问题讨论】:

    标签: javascript angularjs loops model nested


    【解决方案1】:

    您的示例中的 HTML 有点偏离。

    这是working fiddle

    “不工作”input 只是在 ng-model 中有一些代码不工作。

    首先,您不需要在 Angular 指令属性中插入 {{ }}。所以,这包括ng-model。所以{{key}} 不是必需的。

    另外,sourceData 拼写错误。应该是 sourcedata 并且大小写很重要。

    所以ng-model 的最终结果是ng-model="sourcedata[key]"

        <li ng-repeat="(key,value) in sourcedata">
            WORKS: <input type="text" value="{{value}}" /><br/>
            DOESN'T: <input type="text" ng-model="sourcedata[key]" />
        </li>
    

    【讨论】:

    • 首先非常感谢,这些点真的很有帮助。这确实是这里的正确答案。抱歉打错了,我从更复杂的代码中拼凑出一个小提琴,我打错了。最后,你的回答让我意识到我没有准确地表达我的全部问题。我试图做 ng-model="sources[sourcename][key]" 因为我想使用 $scope.sources 数据。我现在就试试……手指交叉!
    • 为了后代,ng-model="sources[sourcename][key]" 工作得很好。
    猜你喜欢
    • 2017-07-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-09
    • 1970-01-01
    相关资源
    最近更新 更多