angularjsangularjs-material

AngularJs form - How to watch for input events?


I want to be able to trigger a function that when one of the form's inputs (not a specific one) is being clicked or focused (doesn't really matters)... then to set a background color for the model window that the form is in.

Here is the marks up

    <md-dialog-content ng-style="{'background-color':newColor}">
  <div class="md-dialog-content">
  <form name="userForm" >
        <div layout-gt-xs="row">
          <md-input-container class="md-block" flex-gt-xs>
            <label>Company</label>
            <input ng-model="user.company">
          </md-input-container>

          <md-input-container>
            <label>Enter date</label>
           <input ng-model="user.date">
          </md-input-container>
        
      </div>

 </form>
  </div>
</md-dialog-content>

I've tried to listen to the event by Angular.element and also by jquery

 angular.element(document.querySelectorAll('[name="userForm"]')).on('focus', function() {
    $scope.newColor = 'red';
  });

But - no luck,

Example


Solution

  • First of all: AngularJS (ie Angular 1) is quite outdated right now. The current version of Angular is Angular 11. Although there is still LTS until end of 2021, for new projects you should consider using a current Angular version.

    As for your question. There are two problems with your code:

    1. The form does not trigger a focus event
    2. When you try to add your eventhandler, the dialog elements are not part of the DOM yet, thus your document.querySelectorAll won't find any elements

    One possibility would be to use the onComplete hook in $mdDialog.show. This will be called, once the show animation is finished, thus, all elements of the dialog template have ben rendered. And in this oncompletehandler, instead of querying for the form, you could query for input elements. It may be necessary to do some further restrictions on the query, because of course you may have additional inputs in the document.

    $mdDialog.show({
      controller: DialogController,
      templateUrl: 'dialog1.tmpl.html',
     
      parent: angular.element(document.body),
      targetEvent: ev,
      clickOutsideToClose: true,
      fullscreen: $scope.customFullscreen, // Only for -xs, -sm breakpoints.
      onComplete: (scope) => {
          angular.element(document.querySelectorAll('input')).on('focus', function() {
             scope.newColor = 'red';
          });
      }
    }