在 AngularJS 中的 ng-repeat 循环中绑定 ng-model [英] Binding ng-model inside ng-repeat loop in AngularJS

查看:27
本文介绍了在 AngularJS 中的 ng-repeat 循环中绑定 ng-model的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试处理 ng-repeat 循环内的范围问题 - 我浏览了很多问题,但还没有完全能够让我的代码工作.

控制器代码:

function Ctrl($scope) {$scope.lines = [{text: 'res1'}, {text:'res2'}];}

查看:

<div ng-controller="Ctrl"><div ng-repeat="line in lines"><div class="preview">{{text}}{{$index}}</div>

<div ng-repeat="line in lines"><-- 在这里输入应该自动更新上面的预览--><input value="{{line.text}}" ng-model="text{{$index}}"/><!-- 这里还有许多其他字段也会影响预览-->

这是一个小提琴:http://jsfiddle.net/cyberwombat/zqTah/

基本上我有一个包含多行文本的对象(它是一个传单生成器).用户可以调整每一行文本(文本、字体、大小、颜色等),我想为它创建一个预览.上面的例子只显示了输入文本的输入字段,我希望它自动/按你输入更新预览 div,但会有更多的控件.

我也不确定我的代码是否适合循环索引 - 这是在循环内创建 ng-model 名称的最佳方法吗?

解决方案

对于 ng-repeat 循环的每次迭代,line 是对数组中对象的引用.因此,要预览值,请使用 {{line.text}}.

同样,要绑定到文本,数据绑定到相同:ng-model="line.text".使用 ng-model 时您不需要使用 value(实际上您不应该使用).

小提琴.

要更深入地了解作用域和 ng-repeat,请参阅 AngularJS 中范围原型/原型继承的细微差别是什么?ng-repeat 部分.

I'm trying to deal with the issue of scope inside of an ng-repeat loop - I've browsed quite a few questions but have not quite been able to get my code to work.

Controller code:

function Ctrl($scope) {
  $scope.lines = [{text: 'res1'}, {text:'res2'}];
}

View:

<div ng-app>
     <div ng-controller="Ctrl">
       <div ng-repeat="line in lines">
           <div class="preview">{{text}}{{$index}}</div>

       </div>
       <div ng-repeat="line in lines">
           <-- typing here should auto update it's preview above -->
           <input value="{{line.text}}" ng-model="text{{$index}}"/>
            <!-- many other fields here that will also affect the preview -->
       </div>
     </div>
    </div>

Here's a fiddle: http://jsfiddle.net/cyberwombat/zqTah/

Basically I have an object (it's a flyer generator) which contains multiple lines of text. Each line of text can be tweaked by the user (text, font, size, color, etc) and I want to create a preview for it. The example above only shows the input field to enter text and I would like that to automatically/as-you-type update the preview div but there will be many more controls.

I am also not sure I got the code right for the looping index - is that the best way to create a ng-model name inside the loop?

解决方案

For each iteration of the ng-repeat loop, line is a reference to an object in your array. Therefore, to preview the value, use {{line.text}}.

Similarly, to databind to the text, databind to the same: ng-model="line.text". You don't need to use value when using ng-model (actually you shouldn't).

Fiddle.

For a more in-depth look at scopes and ng-repeat, see What are the nuances of scope prototypal / prototypical inheritance in AngularJS?, section ng-repeat.

这篇关于在 AngularJS 中的 ng-repeat 循环中绑定 ng-model的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
前端开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆