Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
210 views
in Technique[技术] by (71.8m points)

javascript - Binding ng-model inside ng-repeat loop in AngularJS

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...