0

I was looking this example AngularJS ng-model $scope in ng-repeat is undefined in this question first answered by @Gloopy here http://jsfiddle.net/VnQqH/128/

My question is can I update ng-model values in ng-repeat scope from outside of ng-repeat scope like this:

<div ng-app="MyApp">
<div ng-controller="PostCtrl">
    <div ng-repeat="post in posts">
      <strong>{{post}}</strong>
      <input type="text" ng-model="postText"> 

    </div>

    /*Update ng-model values (in ng-repeat scope) using single click*/

    <a href="#" ng-click="savePost(postText)">save post</a> 
  </div>
</div>

Here is controller:

angular.module('MyApp',[]);

function PostCtrl($scope) {
   $scope.posts = ['tech', 'news', 'sports', 'health'];
   $scope.savePost = function(post){
    alert( 'post stuff in textbox: ' + post);
   }
}

I tried but got undefined :( My experimental fiddle is here http://jsfiddle.net/hot81o2z/ If anyone has the solution for this problem please share. Many thanks in advance.

Community
  • 1
  • 1
tutorialfeed
  • 965
  • 3
  • 11
  • 24

1 Answers1

1

You can make use of $parent in order to pass a scope variable outside of the ng-repeat directive, something like this

HTML:

<div ng-app="MyApp">
    <div ng-controller="PostCtrl">
        <div ng-repeat="post in posts">
          <strong>{{post}}</strong>
          <input type="text" ng-model="$parent.postText"> 

        </div>
       <!--Update on single click-->
        <a href="#" ng-click="savePost(postText)">save post</a>
    </div>
</div>

Controller: Not changed anything, kept what you had

Working Demo

V31
  • 7,626
  • 3
  • 26
  • 44