Angular ng-repeat with controller as syntax

738 views
Skip to first unread message

Chris

unread,
Jun 25, 2014, 2:06:37 PM6/25/14
to ang...@googlegroups.com
I'm using the controller as syntax, which works great for sharing between controller directives, but I can't figure out how to do this with ng-repeat.  It seems to insist that the data is a scope variable (not this) which is not what I want.

    <div ng-controller="StudyCtrl as study">
    {{study.name}}
    
    <input type="text" ng-model="data[0].name">
    <ul>
      <li ng-repeat="item in data">{{item.name}}</li>
    </ul>

    <div ng-controller="OtherCtrl as other">
         {{study.name}} <!-- I can access this! -->
         <input type="text" ng-model="study.name"> <!-- I can even change on both ctrls -->
         
         <input type="text" ng-model="data[0].name"> <!-- this will update in both ctr   inputs, but not on the ng-repeat! -->
    </div>

    // in my controller I would have 
    this.name = "myname";
    // using $scope.data = {} works, but then I don't have full access to it


The point of this is, I have an ng-repeat with one controller and scope and a form that allows the user to edit this data with another controller and scope-  When there is a change, it needs to be reflected in both spots and I'm trying to avoid root scope or passing objects back and forth in services.
Thanks for the help!

Chris

unread,
Jun 25, 2014, 2:54:55 PM6/25/14
to ang...@googlegroups.com

André Farzat

unread,
Jun 25, 2014, 4:40:58 PM6/25/14
to ang...@googlegroups.com
The problem is that you're not referencing the object property in the ng-model, you're referencing the primitive `this.name`.This way, ng-repeat and ng-model's point to different variables/properties.

I forked your fiddle and added a $watch to make it work: http://jsfiddle.net/andrefarzat/z3D5H/1/

Hope this helps.

On Wednesday, June 25, 2014 3:54:55 PM UTC-3, Chris wrote:
fiddle example: http://jsfiddle.net/squirrelradio/LZEbT/

Chris

unread,
Jun 27, 2014, 10:12:41 AM6/27/14
to ang...@googlegroups.com
Thank you for the reply!  I find it very difficult to get responses and good information with Angular questions (much harder than common JavaScript or jQuery stuff).

So the reason for this is, I have 2 controllers, one that grabs a data object from the service and fills a list, and the other controller has to display that same data editable, and as the user changes, it should change in the list as well.
So would you agree, this would be the "best practice" way to handle this ?

Thanks again Andre!
Reply all
Reply to author
Forward
0 new messages