2013-02-15 51 views
1

我正在嘗試編寫一個應用於輸入元素的可配置指令,該輸入元素需要ngModel,併爲ngModel添加了解析器和格式化函數。角度輸入格式化程序/分析程序指令和插值屬性?

我遇到的問題是,我似乎無法將插值插入指令,同時支持ngModel綁定。舉例來說,我希望能夠用我的指令在以下兩種方法之一:

傳遞文字形參:

<input ng-model="foo" my-directive="120" /> 

或通過插值參數從目前的範圍:

<input ng-model="foo" my-directive="{{bar}}" /> 

... 
function MyCtrl($scope) { 
    $scope.bar = "120"; 
} 

如果我在我的指令定義中讀取了鏈接函數的attributes參數,我可以在第一次使用中獲取attributes.myDirective的值,但在第二次使用中,myDirective的值未定義。現在

,如果我添加一種分離的範圍,以該指令定義:

scope: { myDirective: '@' } 

然後scope.myDirective被定義,並在場景中上述內插,但現在ngModel壞了。我的解析器/格式化程序函數傳遞給它們的輸入參數未定義。發生了什麼,以及我如何實現我想要的行爲?

指令:

module.directive('myDirective', function() { 
     return { 
      restrict: 'A', 
      require: 'ngModel', 
      replace: false, 
      link: function (scope, elm, attrs, ctrl) { // attrs.myDirective not interpolated 
+0

你能發佈你的指令代碼嗎?我的直覺是,你可能沒有使用'require'鍵,它可以讓你訪問'ngModel'控制器。 – satchmorun 2013-02-15 16:42:17

回答

2

當您添加隔離範圍中,將打造全新的子範圍不從與ngModel的在它的值範圍繼承。這就是爲什麼你的解析器和格式化程序變得不確定。

而且,在你的榜樣,以獲得在bar值,你不需要它在大括號:

<input ng-model='foo' my-directive='bar' /> 

而在你的鏈接功能:

link: function(scope, element, attr, ctrl) { 
    attr.myDirective == 'bar'. 
    scope.$eval(attr.myDirective) == // whatever the value of 'bar' is in the current scope 
} 

所以你不需要隔離範圍。只需使用scope.$eval來評估傳遞給您的指令的表達式。

Here's a quick fiddle