2015-06-21 110 views
0

我在AngularJS中使用了一個指令,我試圖檢查我的字段是否是$ dirty,如果這是真的我想記錄一條消息,當它發生變化時我想顯示另一條消息(這句話稍後將被替換爲更復雜的東西)。Angular指令不看

我想在所有的輸入中重用我的指令,但我不能。提前致謝。

<input ng-edited ng-model="stakeholder.nombre" name="nombre" type="text"> 

我的指示是:

MetronicApp.directive('ngEdited', function() { 
    return { 
     restrict: 'A', 
     require: ['^form', 'ngModel'], 
     link: function (scope, elem, attrs, req) { 
      scope.elemDirty = req[1].$dirty; 
      scope.elemName = req[1].$name; 
      var doFunction = function() { 
       if (scope.elemDirty) { 
        console.log("true"); 
       } else { 
        console.log("false"); 
       } 
      }; 
      scope.$watch(scope.elemName, doFunction, true); 
     } 
    }; 
}); 
+0

我不確定在這個例子中'req [1]'是什麼。通常一個控制器作爲第四個參數傳遞給鏈接函數。 – Claies

+0

@Claies我正在發送第4個arg中的兩個項目:form和ngmodel,你可以在require中看到它 –

回答

1

基於this answer,爲什麼不嘗試

link: function (scope, elem, attrs, ngModel) { 
    var doFunction = function (isDirty) { 
     if (isDirty) { 
      console.log("true"); 
     } else { 
      console.log("false"); 
     } 
    }; 
    scope.$watch(function(){return ngModel[1].$dirty;},doFunction); 
} 

See plunker

編輯

我注意到在你的問題中,你正試圖觀察元素名稱的變化。我不知道你將如何改變這種屬性,但如果你是,使用attrs.$observe

attrs.$observe('name', doFunction); 
+0

nope,它不工作:-(,仍然沒有看到變化 –

+0

@JeanCedron笨拙的作品,請你說明一下不適合你? – Yaelet

1

如果你使用一個參數(而不是字符串),你需要從一個函數返回它:

scope.$watch(function() { 
    return scope.elemName; 
}, doFunction, true); 
+0

我也試過這個,但它不工作,它沒有看任何改變 –

+0

@JeanCedron你能提供一個小提琴嗎? –