AngularJS双向数据绑定在指令中无法正常工作 [英] AngularJS two-way data binding not working properly in directive

查看:135
本文介绍了AngularJS双向数据绑定在指令中无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用ng-repeat实现单选按钮列表. typeList.html

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>

指令:

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'
        };


    });

指令具有隔离范围.我要传递两个参数.单选按钮和要在父范围中存储答案(id-上次单击单选按钮)的结果对象要打印的列表.不幸的是,每当我单击单选按钮时,结果只会在本地更改.

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;

我将不胜感激.

推荐答案

您必须将非原始对象传递给模型,以获取两战绑定的参考.只需将selected包装到一个对象中以供参考.

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.

在您的控制器中使用.

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

'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}}

工作小提琴演示

希望有帮助.

这篇关于AngularJS双向数据绑定在指令中无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆