2016-02-08 17 views
0

This plunk表單的字段只允許輸入aaa。請注意,錯誤消息是在控制器中設置的,而不是在html中。當用戶點擊Submit時,他們應該看到消息,但消息未顯示。這段代碼有什麼問題?如何使用動態ngMessages驗證表單

HTML

<body ng-app="ngMessagesExample" ng-controller="ctl"> 

    <form name="myForm" novalidate ng-submit="submitForm()"> 
    <label> 
     This field is only valid when 'aaa' is 
     <input type="field1" 
      ng-model="data.field1" 
      name="field1" 
      required /> 
    </label> 
    <div ng-messages="myForm.field1.$error" style="color:red"> 
     <div ng-message-exp="required">{{errorMsg}}</div> 
    </div> 

    <br/><br/> 
    <button style="float:left" type="submit">Submit</button> 
</form> 

</body> 

的Javascript

var app = angular.module('ngMessagesExample', ['ngMessages']); 

app.controller('ctl', function ($scope) { 

    $scope.submitForm = function() { 
    if ($scope.field1 != 'aaa') 
     $errorMsg = "This field should be 'aaa'"; 
    else 
     $errorMsg = ""; 
    };  

}); 

回答

1

忘了我以前的答案。 最簡單也最健壯的是實際制定新指令。

var app = angular.module('ngMessagesExample', ['ngMessages']); 
app.directive("aaa", function() { 
    return { 
     restrict: "A", 

     require: "ngModel", 

     link: function(scope, element, attributes, ngModel) { 
      ngModel.$validators.aaa = function(modelValue) { 
       return modelValue === 'aaa'; 
      } 
     } 
    }; 
}); 

而且你的控制器:

app.controller('ctl', function ($scope) { 

    $scope.data = { 
    field1: "" 
    } 
    $scope.submitForm = function(){ 
    //extra whatever code 
    } 
}); 

你的HTML應該是這樣的:

<body ng-app="ngMessagesExample" ng-controller="ctl"> 
    <form name="myForm" novalidate ng-submit="submitForm(myForm)"> 
    <label>This field is only valid when 'aaa' is</label> 
    <input type="field1" 
     ng-model="data.field1" 
     name="field1" 
     required aaa/> 
    <div ng-messages="myForm.field1.$error" style="color:red"> 
     <div ng-message="required">FIELD IS REQUIRED!!</div> 
     <div ng-message="aaa">FIELD MUST BE 'aaa'</div> 
    </div> 
    <button style="float:left" type="submit">Submit</button> 
    </form> 
</body> 
+0

我更新了普拉克根據您的意見[這裏](https://plnkr.co/編輯/ UKTHa2VhjfMLTst3JSdG?p =預覽),但它不起作用,有什麼想法?謝謝 – ps0604

+0

我更新了答案,並更新了你的plunk。 – dendimiiii