0

I want to add error message, something like this:

  <md-input-container>
    <label>Last Name</label>
    <input name="lastName" ng-model="lastName" required>
    <div ng-messages="userForm.lastName.$error" ng-show="userForm.lastName.$dirty">
      <div ng-message="required">Here is some message</div> 
    </div>
  </md-input-container>

But want to call rendering from controller:

callMessage() {
// How can I implement this?
}
2
  • Do you already have an Angular controller set up? Commented Jan 20, 2017 at 12:41
  • Yes. I have set up. Commented Jan 20, 2017 at 12:48

3 Answers 3

1

I assume you are not using controller as syntax, so you will have to define a function on the $scope object within your controller:

function YourController($scope,...){

   $scope.callMessage = function(){
      //you can access your form using $scope.userForm
      return "yourString";
   }
}

Your markup would change as follows:

<md-input-container>
  <label>Last Name</label>
  <input name="lastName" ng-model="lastName" required>
  <div ng-messages="userForm.lastName.$error" ng-show="userForm.lastName.$dirty">
  <div ng-message="required">{{callMessage()}}</div> 
</div>

The important part is that you define your function on the $scope so that Angular actually can bind the {{callMessage()}} part in the markup to your function.

Sign up to request clarification or add additional context in comments.

Comments

0

You may do,

 <md-input-container>
  <label>Last Name</label>
  <input name="lastName" ng-model="lastName" required>
  <div ng-messages="userForm.lastName.$error" ng-show="vm.callMessage(userForm.lastName.$dirty)">
  <div ng-message="required">{{vm.myMessage}}</div> 
</div>

And from controller

callMessage(isDirty) {
 // Your conditional message with respect to "isDirty" parameter
 isDirty ? this.myMessage = 'Dirty Message' : false;
 return isDirty;
}

Comments

0

You may call directly $error in your controller after you have set up form.

View

<md-input-container>
        <label>Last Name</label>
        <input name="lastName" ng-model="lastName" required>
        <div ng-messages="userForm.lastName.$error" ng-show="userForm.lastName.$dirty">
          <div ng-message="required">{{errorMsg}}</div> 
        </div>
      </md-input-container>

Controller

 var isError = $scope.userForm.lastName.$error;

 if (isError) {
    $scope.errorMsg = 'Hey, this is error message';
 }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.