Directive's isolated scope object is undefined

2019-08-13 03:03发布

问题:

I'm new to AngularJS and trying to understand how to bind a directive's isolated scope with view's ng-model. The form should be valid when either inputs are empty or both filled with some values. Help me to find out why do I get "undefined" in a console log:

.html:

<form name="recipientsForm" novalidate>
    <md-input-container>
        <label>Name</label>
        <input name="name" type="text" ng-model="relationship.name" value="" empty-or-both-filled="relationship.relationshipType">
        <div ng-messages="recipientsForm.name.$error">
            <div ng-message="emptyOrBothFilled">Enter name.</div>
        </div>
    </md-input-container>
    <md-input-container>
        <md-select name="type" placeholder="Select your relation... " ng-model="relationship.relationshipType" empty-or-both-filled="relationship.name">
            <md-option ng-repeat="type in relationshipTypes" value="{{type.relationshipType}}">
                {{type.name}}
            </md-option>
        </md-select>
        <div ng-messages="recipientsForm.type.$error">
            <div ng-message="emptyOrBothFilled">Pick relationship.</div>
        </div>
    </md-input-container>
</form>

Here is the .js file:

(function () {
    'use strict';

    angular
        .module('app')
        .directive('emptyOrBothFilled', [emptyOrBothFilled]);

    function emptyOrBothFilled() {
        return {
            restrict: 'A',
            require: 'ngModel',
            scope: {
                targetNgModel: '=emptyOrBothFilled'
            },
            link: function($scope, element, attrs, ngModel) {
                ngModel.$validators.emptyOrBothFilled = function(val) {
                    console.log($scope.targetNgModel);
                    return (!val && !$scope.targetNgModel) || (!!val && !!$scope.targetNgModel);
                }

                $scope.$watch('targetNgModel', function() {
                    ngModel.$validate();
                })
            }
        }
    }
})();

Why console.log($scope.targetNgModel); output is "undefined"? Thanks.

回答1:

Rather than building your own directive, I recommend using the built in ng-required on the input. Try it below. The message will appear if either field is not empty and will disappear if both are either empty or have a value.

However, if you prefer to use a custom directive, I've included an implementation that you can try. You can't use $scope.targetNgModel as you've done it, but you can use: scope.$eval(targetNgModel). Note that you can use $isEmpty to check for undefined or empty values.

var app = angular.module('required.demo', []);
app.controller('MyCtrl', function($scope) {

});
app.directive('emptyOrBothFilled', [
  function() {
    return {
      restrict: 'A',
      scope: true,
      require: 'ngModel',
      link: function(scope, elem, attrs, ctrl) {
        var checker = function() {
          //get the value of the first input
          var e1 = scope.$eval(attrs.emptyOrBothFilled);
          //get the value of the second input  
          var e2 = scope.$eval(attrs.ngModel);
          
          if (ctrl.$isEmpty(e1) || ctrl.$isEmpty(e2)) {
            return ctrl.$isEmpty(e1) && ctrl.$isEmpty(e2);
          }
          
          
        };
        scope.$watch(checker, function(newval, oldval) {
          //set the form control to validity with the value of the checker function
          if (newval !== oldval) {
            ctrl.$setValidity("emptyorboth", newval);
          }
        });
      }
    };
  }
]);
<script src="https://code.angularjs.org/1.3.15/angular.js"></script>
<div ng-app="required.demo">
  <h3>Using ngRequired</h3> 
  <form name="myform" novalidate>
    <input type="text" name="name" ng-model="name" ng-required="fullname" />
    <input type="text" name="fullname" ng-model="fullname" ng-required="name" />
    <p ng-show="myform.name.$error.required || myform.fullname.$error.required">You must fill in both fields</p>
  </form>
  <hr>
  <div ng-controller="MyCtrl">
    <h3>Using Custom Directive</h3> 
    <form name="myform2" novalidate>
      <input type="text" name="name" ng-model="relationship.name" />
      <input type="text" name="relationship" ng-model="relationship.relationshipType" empty-or-both-filled="relationship.name" />
      <p ng-show="myform2.relationship.$error.emptyorboth">You must fill in both fields</p>
    </form>
  </div>
</div>