2014-10-17 150 views
0

我正在爲某些添加的功能創建自定義輸入指令。角度指令雙向綁定問題

app.directive('myTextInput', [ 
    function() { 
     var directive = {}; 
     directive.restrict = 'A'; 
     directive.scope = { 
      textModel: '=' 
     }; 
     directive.link = function ($scope, element, attrs) { 
      // FUnctionality 
     }; 
     directive.template = '<input ng-model="textModel" type="text">'; 
    return directive; 
}]); 

和所用的分離的範圍屬性textModel爲雙向綁定。 和父範圍HTML是:

<div my-text-input text-model="myScopeVariable"></div> 
<span>TYPED : {{myScopeVariable}}</span> 

控制器範圍具有定義的變量$scope.myScopeVariable="";

當我這樣做。 在指令輸入中輸入的內容可以在<span>標籤中打印。 這告訴它正在更新。

問題是。

在父範圍內。我有一個方法,將執行按鈕單擊。

$scope.doSomething = function(){ 
    console.log($scope.myScopeVariable); 
}; 

點擊按鈕。日誌是空的。這應該是指令輸入中輸入的內容。

這就奇怪了

現在,如果定義範圍變量

$scope.myScopeVariable = {key:''}; 

和在HTML中使用如

<div my-text-input text-model="myScopeVariable.key"></div> 
<span>TYPED : {{myScopeVariable.key}}</span> 

然後它工作的每一個地方。即使在以前說的功能doSomething()

任何想法發生了什麼?

+0

Hrmm,我試着重現這個問題,但對我來說看起來很好。 http://plnkr.co/edit/SyRPmIvxvnAw7CPBv2NJ?p=preview – CozyAzure 2014-10-18 06:42:17

回答

0

這是因爲myScopeVariable包含的值爲字符串
所以,如果你改變從指令的文本框的值。它不會被反映。

而在第二種方法中,您指的是對象。所以每當你改變對象的值時,就調用它的相關的監視方法。價值將被更新。

0

my-text-input是一個指令,所以他有自己的範圍,所以模型myScopeVariable不是由父母監視。

嘗試這樣的:

<div my-text-input text-model="$parent.myScopeVariable"></div> <span>TYPED : {{myScopeVariable}}</span>

這是不是最好的做法,但它可能工作。