2015-07-04 84 views
1

在下面的指令中,我們如何在通過指令中的屬性傳遞的其他元素上手動設置驗證。下面的代碼給出了錯誤otherField不存在,而它應該取這個變量的值,而不是直接在作用域字符串中的這個字段的名稱。從示波器角度動態訪問元素

app.directive('higherThan', [ 
    function() { 

    var link = function($scope, $element, $attrs, ctrl) { 

     var otherField = $attrs.otherField; 
     $scope.otherField.$setValidity('lowerThan', true); 
     //Other details of directive not kept for simplicity 
    } 

    return { 
     require: 'ngModel', 
     link: link 
    }; 

    } 
]); 

HTML

<form name="main_form"> 
<label>From</label> 

<input name="from_date" type="text" class="form-control" ng-model="date_range[0]" lower-than="date_range[1]" ng-required="true" close-text="Close" /> 

<label>To</label> 

<input name="to_date" type="text" class="form-control" ng-model="date_range[1]" higher-than="date_range[0]" ng-required="true" close-text="Close" other-field="from_date"/> 

<span ng-show="main_form.to_date.$error.higherThan">From date should be lower than to date</span> 
</form> 
+0

你能告訴我們你的HTML嗎? –

回答

1
var otherField = $attrs.otherField; 
$scope.otherField.$setValidity('lowerThan', true); 

有幾個在這裏的問題:

1)var otherField是一個字符串,而不是實際的輸入。

2)一旦你設置了var otherField你實際上並沒有使用它。

3)沒有財產$scope.otherField,這就是爲什麼你會收到錯誤。

即使你做了$scope[otherField]這會出錯,因爲ngModelController爲from_date不屬於$scope它屬於main_form

您應該嘗試使用console.log($scope)進行調查。

它應該是:

app.directive('higherThan', [ 
    function($parse) { 

     var link = function($scope, $element, $attrs, ctrl) { 

      var otherField = $parse($attrs.otherField)($scope); 
      otherField.$setValidity('lowerThan', true); 
      //Other details of directive not kept for simplicity 
     } 

     return { 
      require: 'ngModel', 
      link: link 
     }; 

    } 
]); 


<form name="main_form"> 
    <label>From</label> 
    <input name="from_date" type="text" class="form-control" ng-model="date_range[0]" lower-than="date_range[1]" ng-required="true" close-text="Close" /> 
    <label>To</label> 
    <input name="to_date" type="text" class="form-control" ng-model="date_range[1]" higher-than="date_range[0]" ng-required="true" close-text="Close" other-field="main_form.from_date" /> 
    <span ng-show="main_form.to_date.$error.higherThan">From date should be lower than to date</span> 
</form> 
+0

謝謝,對解析東西和將字符串轉換爲變量名稱感到困惑! – virtualfireofhopes

0

$setValidity應該叫上NgModelController對象:

var link = function($scope, $element, $attrs, ctrl) { 

    var otherField = $attrs.otherField; 
    ctrl.$setValidity('lowerThan', true); 
    //Other details of directive not kept for simplicity 
}