[英]AngularJS - ngModel conflicts with custom directive
I have this html: 我有这个HTML:
<select id="mainVideo" class="form-control" required-select
ng-model="qtTestData.mainVideo"
ng-options="mainVideo for mainVideo in mainVideoSources"
ng-change="getSelectedData(qtTestDataBuffer,'mainVideo', qtTestData.mainVideo)"
name="mainVideo"
ng-required="true">
</select>
The function getSelectedData() takes 3 arguments, and 3rd is ngModel. 函数getSelectedData()带有3个参数,第3个是ngModel。 Everything works if I do not use my custom directive required-select .
如果我不使用自定义指令required-select,一切都会正常。 My directive:
我的指令:
App.directive('requiredSelect', function () {
return {
restrict: 'AE',
require: 'ngModel',
link: function(scope, element, attributes, ngModel) {
ngModel.$validators.requiredSelect = function(modelValue, viewValue) {
var value = modelValue || viewValue;
var requiredSelect = 'Please, select a value'; //TBD.. select first ngOption
return value != requiredSelect;
};
}
};
}); });
If I include required-select directive into HTML, my ngModel becomes qtTestData.mainVideo == undefined
by default and as result I have crashes... Looks like ngModel has been overwritten by the directive... 如果我在HTML中包含required-select指令,则默认情况下,我的ngModel变为
qtTestData.mainVideo == undefined
,结果我崩溃了...看起来ngModel已被指令覆盖...
Does someone know how to fix it? 有人知道如何解决吗? Thanks,
谢谢,
There's nothing wrong with your directive, If you never set $scope.qtTestData.mainVideo
it will automatically be undefined
. 您的指令没有任何问题,如果您从未设置
$scope.qtTestData.mainVideo
,它将自动为undefined
。 Set it first to some default value, and your code will just work. 首先将其设置为一些默认值,您的代码将正常工作。
.controller('YourController', function($scope){
$scope.mainVideoSources = [
'Please, select a value',
'A',
'B'
];
$scope.qtTestData = {
mainVideo: 'Please, select a value'
};
});
The issue was fixed by removing 该问题已通过删除解决
ng-required="true"
from the element where custom directive is applied. 从应用自定义指令的元素开始。 As I understand, we should not use
ng-required="true"
with $validators
on one element 据我了解,我们不应在一个元素上将
ng-required="true"
与$validators
使用
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.