Hi,
I am trying to create a simple way for the server side to return an error
associated with a JSON path and have that information translate to a field
error. For example, if the server returns:-
{ "errorMessage": "Code not valid when you say you want to leave on a
Tuesday", "field" : "room[1].stay.code" }
And I can then target the field directly. One way I thought about making
this work is to make sure every value is an object and add a $$error where
an error occurs. So, if you have this:-
$scope.room[1].stay.code
Then there would be some code which turns that value into an object (in
case it isn't already) and adds $$error to that object as the message.
Like so:-
$scope.room[1].stay.code.$$error = 'Code not valid when you say you want to
leave on a Tuesday';
I have tried to achieve this with a directive:-
<input type="text" name="fruitName" ng-model="data.value"
serverError="data.value.$$error" />
In this case serverError would be a path to the $$error value.
var app = angular.module('angularjs-starter', []);
app.controller('MainCtrl', function($scope) {
$scope.doSomething = function () {
alert('Submitted!');
}
$scope.data = {};
$scope.data.value = new String('blah');
$scope.data.value.$$error = 'My Error';
$scope.data.toggleError = function() {
if ($scope.data.value.$$error) {
$scope.data.value.$$error = null;
}
else {
$scope.data.value = new String($scope.data.value);
$scope.data.value.$$error = "SOME ERROR";
}
};
});
app.directive('input', function (){
return {
require: 'ngModel',
restrict: 'A',
scope: { serverError : "=serverError" },
link: function(scope, elem, attr, ctrl) {
var verificationFunction = function(viewValue) {
if(scope.serverError) {
ctrl.$setValidity('serverError',true);
return viewValue;
}
else {
ctrl.$setValidity('serverError',false);
return undefined;
}
};
ctrl.$parsers.unshift(verificationFunction);
ctrl.$formatters.unshift(verificationFunction);
verificationFunction();
}
};
});
I have a plunkr with my attempt:-
http://plnkr.co/edit/Ug9oM1LNqPpTsONhRTnG?p=preview
Now, I have had some success with 1.1.4, except that it does not seem to
mark the form as invalid (but it does mark the field as invalid). Also,
as soon I change the version to anything greater than that (eg 1.1.5) it
stops working completely.
What am I doing wrong?
Thanks.
Kamal.
--
You received this message because you are subscribed to the Google Groups
"AngularJS" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
To post to this group, send email to [email protected].
Visit this group at http://groups.google.com/group/angular.
For more options, visit https://groups.google.com/d/optout.