2016-04-18 8 views
1

コントローラは状態で呼び出されます。オブジェクト(変数)を指令angjsに渡す

.controller('test', function($scope) { 
    $scope.variable = 'Hello'; 
    $scope.other = 'Hi'; 
}) 
.directive('customDir', function() { 
    return { 
     restrict: 'A', 
     link: function($scope, element, attrs) { 
      attrs.customDir += ' Word'; 
     } 
    } 
}); 

<input type="text" custom-dir="variable" /> 
<div>{{variable}}</div> 

<input type="text" custom-dir="other" /> 
<div>{{other}}</div> 

私は$ scope.variableと$ scope.other "ことば" を受け取るには、ディレクティブで渡された変数の値を変更することができなければならないことが必要です。

+0

外部変数を変更できるように指示しますか? – dfsq

+0

'input'ボックスに入力されたものに基づいて'変数 'だけを変更する指令について質問していますか? – CShark

+0

@ dfsq Yeeah .... – paulorwd

答えて

0

方法はいくつかあります。

.directive('customDir', function() { 
    return { 
     link: function(scope, element, attrs) { 
      scope[attrs.customDir] += ' Word'; 
     } 
    } 
}); 

デモ:新しい孤立範囲を必要としない場合http://plnkr.co/edit/zQOMttjnbvdf6OJNOeoq?p=preview

もう1:

.directive('customDir', function() { 
    return { 
     scope: {customDir: '='}, 
     link: function(scope, element, attrs) { 
      scope.customDir += ' Word'; 
     } 
    } 
}); 

デモ:最初の1は、結合、双方向を使用することですhttp://plnkr.co/edit/FmIy3z4t1SEJQn1YQAkP?p=preview

+0

2番目のアプローチの問題'attrs.customDir'が単に" variable "ではなく" model.variable "であればどうでしょうか?私は' scope ['variable'] 'は動作しますが、scope ['model.variable']'は意味しません。 2番目のplunkrをフォークして、 '$ parse'でそのケースを処理するバージョンを作成してください。http://plnkr.co/edit/jj6Ls7SkY6eUYihPdttu?p=info – CShark

+0

@dfsq Perfect !!ちょうどスコープ変数に$タイムアウトを入れなければなりません(customDir)常に前の値を渡していたためです。 – paulorwd