简体   繁体   中英

using ng-model in ng-repeat

I've created angular directive with template:

<div class="directiveclass">
   <div ng-repeat="i in items">
       <input type="radio" ng-model="myvalue" value="{{$index}}">
   </div>    
</div>

The ng-model "myvalue" is part of the directive local scope:

.directive('mydirective', function()
{
    return {
        templateUrl: "path",
        scope: {},
        link : function(scope, el, attr)
        {
            scope.myvalue = 0;   
            scope.$watch('myvalue', function()
            {
                console.log('myvalue changed');
            });
        }
    };
}

I'm clicking on the the radio buttons elements, but "myvalue" value never change.

Any idea?

Sample code: http://jsfiddle.net/r5jGL/

I found the solution. Since ng-repeat create new scope, I've changed the ng-model value to $parent.myval in order to access the directive scope.

In the HTML:

<input type="radio" ng-model="$parent.myvalue" value="{{$index}}">

This allows you to access ng-model as ng-repeat has created its own scope.

The directive does not need to be changed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM