AngularJS two-way data binding not working properly in directive

纵饮孤独 提交于 2020-01-24 00:29:08

问题


i am trying to implement radio-button list using ng-repeat. typeList.html

<div ng-repeat="type in types" >
    <input type="radio" id={{type.id}} name="{{type.name}}"  ng-model="result" ng-value="type.id" >
    {{type.name}}
    <div> Result {{result}} </div> //result is changing only in the row of clicked radio-button. It should change in every row.(two way data-binding).
</div>

Directive:

angular.module('app').directive('myList',function(){
        return{
            restrict: 'A',
            scope: {
                types: '=',   //here list is passed to be printed with ng-repeat
                result: '='   //here I want to store which radio-button was selected last time by id
            },
            templateUrl: 'html/typeList.html'
        };


    });

Directive has isolated scope. I am passing two parameters. List to be printed with radio buttons and result object which stores answer(id-what radio button was clicked last time) in parent scope. Unfortunately whenever i click on radio-buttons my result is changing only locally.

 Passing parameters to my directive.
 <div my-list types="list" result="selected"></div>



  Passed list and result paramater from controller to myList directive.

 $scope.list   = [
        { id: 1, name:'Name 1' },
        { id: 2, name:'Name 2' },
        { id: 3, name:'Name 3' }
    ];

$scope.selected = -1;

I would be grateful for any help.


回答1:


You have to pass a non-primitive object to the model to get its reference for two-war binding. Just wrap selected into an object for its reference.

In your controller use.

$scope.list = [{
    id: 1,
    name: 'Name 1'
  }, {
    id: 2,
    name: 'Name 2'
  }, {
    id: 3,
    name: 'Name 3'
  }];
  $scope.ctrlModel = {
    selected: -1
  }

And in the Markup that is 'html/typeList.html'

<div ng-repeat="type in types" >
  <input type="radio" id={{type.id}} ng-model="result.selected" ng-value="type.id" >
     {{type.name}}
</div>
Result {{result.selected}}

Working Fiddle Demo

Hope it helps.




回答2:


try to have scope variables as object like

$scope.types = { list: {}, selected: 'radioValueThatNeedsToBeSelected' }



来源:https://stackoverflow.com/questions/38306365/angularjs-two-way-data-binding-not-working-properly-in-directive

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!