2013-11-28 17 views
6

角度ディレクティブのデモ:今すぐ角度指令:親スコープ内の変数にバインド

jsfiddle

<div ng-app="myApp"> 
<script> 
    function Contrl($scope){ 
     $scope.parval = 0; 
     $scope.items = [ 
      {id: 1, text: '1'}, 
      {id: 2, text: '2'}, 
      {id: 3, text: '3'} 
     ]; 
    } 
</script> 
<div ng-controller="Contrl"> 
    A: <input type="radio" value="1" ng-model="parval">1</input> 
    <input type="radio" value="2" ng-model="parval">2</input> 
    <input type="radio" value="3" ng-model="parval">3</input> 
    <item parval="parval" items="items"></item> 
</div> 

angular.module('myApp', []) 
.directive('item', function() { 
    return { 
     restrict: 'E', 
     replace: true, 
     scope: { 
      parval: '=', 
      items: '=' 
     }, 
     template: '<div>' + 
     'B: <span ng-repeat="i in items">' + 
       '<input value="{{i.id}}" type="radio" ng-model="parval">{{i.text}}</input>&nbsp;' + 
      '</span>' + 
     '</div>' 
    }; 
}); 


はA1をクリックします - > B1は
クリックしてA2を選択 - > B2選択

クリックB1 - > A1が
クリックB2を変更していない - > A2

を変更していない私が欲しい:
は はA1をクリックします - > B2選択

クリックB1 - - > A1> B1
選択A2をクリックします選択
B2を選択 - > A2を選択

どのようにですか?

答えて

4

ng-repeatは新しいスコープを作成するため、リテラル表記を使用するのではなく、避けるべきプリミティブを使用しています。以下のコードは、子コンポーネントに親から値を渡すため

<div ng-controller="Contrl"> 
    A: <input type="radio" value="1" ng-model="parval.value">1</input> 
    <input type="radio" value="2" ng-model="parval.value">2</input> 
    <input type="radio" value="3" ng-model="parval.value">3</input> 
    <item parval="parval" items="items"></item> 
</div> 
    <script> 
     function Contrl($scope) { 
      $scope.parval = { value: 0 }; 
      $scope.items = [ 
       { id: 1, text: '1' }, 
       { id: 2, text: '2' }, 
       { id: 3, text: '3' } 
      ]; 
     } 
     angular.module('myApp', []) 
.directive('item', function() { 
    return { 
     restrict: 'E', 
     replace: true, 
     scope: { 
      parval: '=', 
      items: '=' 
     }, 
     template: '<div>' + 
     'B: <span ng-repeat="i in items">' + 
       '<input value="{{i.id}}" type="radio" ng-model="parval.value">{{i.text}}</input>&nbsp;' + 
      '</span>' + 
     '</div>' 
    }; 
}); 
    </script> 
+0

をあなたの問題を解決します{ text: '<' }というバインディングを使うことができますが、子と親の間で何をする必要がありますか? (tetは親から子供に表示されます) – cracker

5

一つの方法は、$親 (NG-モデル= "$のparent.parval")を使用することです

angular.module('myApp', []) 
.directive('item', function() { 
    return { 
     restrict: 'E', 
     replace: true, 
     template: '<div>' + 
     'B: <span ng-repeat="i in items">' + 
       '<input value="{{i.id}}" type="radio" ng-model="$parent.parval">{{i.text}}</input>&nbsp;' + 
      '</span>' + 
     '</div>' 
    }; 
}); 
関連する問題