我是新来AngularJS,并试图了解如何将指令的隔离范围绑定视图的NG-模型。 当任一输入是空的或两者填充有一些值的形式应该是有效的。 帮我看看为什么我在控制台日志得到“未定义”:
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>
这里是.js文件:
(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();
})
}
}
}
})();
为什么执行console.log($ scope.targetNgModel); 输出“未定义”? 谢谢。