问题
What is the correct way to check ngModelController validity?
I have a valid controller object inside of a directive. If I log the object to the console from inside the directive I get:
console.log(ctrl)
$dirty: false
$invalid: true
$modelValue: ""
$name: undefined
$pristine: true
$valid: false
$viewValue: ""
...
then, if I ask if( ctrl.$valid === true )
to log the object to the console again, it does with the exact same output.
console.log(ctrl); //ctrl.$valid is false
if(ctrl.$valid == true) {
console.log(ctrl); //ctrl.$valid is false
}
additionally if I inspect the element I can see the the appropriate ng-invalid
class is being applied.
I will try to make a plunkr to demonstrate but I can't imagine I would be able to duplicate this.
Update If I console.log(ctrl.$valid)
is prints true
. So now I get how it's passing the conditional but not why the object form shows $valid
being false
.
Also I made a plnkr that shows an example of what I am doing but it does not suffer from the same problem. example
回答1:
Have you tried this:
console.log(JSON.stringify(ctrl));
if(ctrl.$valid == true) {
console.log(JSON.stringify(ctrl));
}
or
console.log("$valid is ", ctrl.$valid);
if(ctrl.$valid == true) {
console.log("$valid should be true and is actually ", ctrl.$valid);
}
It could be related to this (old) Chrome bug. I believe the expected behavior is that when you expand the object in the console you get the value of the object at expansion time, not at log time, so you would need to print the object as a string or clone it when logging.
Edit - Some more details...
If you run this var obj = {a: 1, b: {}}; console.log(obj); obj['a'] = 2; console.log(obj);
in the Chrome console you will see this being output:
> Object {a: 1, b: Object}
a: 2
b: Object
__proto__: Object
> Object {a: 2, b: Object}
a: 2
b: Object
__proto__: Object
Edit 2
Hopefully this will answer your question. It appears that you may be adding a parser to the $parsers
array after $setViewValue(...)
has been called. As a result, when your directive is first initialized any validations you have added will not have been executed. You can manually execute them by calling something like ctrl.$setViewValue(ctrl.$viewValue);
after your parser has been added.
来源:https://stackoverflow.com/questions/21445555/angularjs-ngmodelcontroller