【发布时间】:2015-07-03 17:40:48
【问题描述】:
我是 AngularJS 的新手,并试图了解如何将指令的隔离范围与视图的 ng-model 绑定。当任一输入为空或都填充了某些值时,表单应该是有效的。帮助我找出为什么我在控制台日志中得到“未定义”:
.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);输出是“未定义”?谢谢。
【问题讨论】:
-
在标记中它应该是空的或两者都填充
-
抱歉,我不清楚你的意思。
-
请忽略。我搞混了。
-
如果您解释一下您要做什么,也许会有所帮助。我没有遵循你的代码。你认为 $scope.targetNgModel 来自哪里?
-
啊,现在我想我跟着了。我想你可以在指令中做到这一点。我不得不考虑一下。但是我会如何使用 ngRequired。如果其他模型未定义,则将字段设为必填。
标签: angularjs angularjs-directive