Reputation: 13342
When I trying to do server-side validation on my "name"-field, by adding a directive:
app.directive('uniqueName', function($http) {
var toId;
return {
require: 'ngModel',
link: function(scope, elem, attr, ctrl) {
scope.$watch(attr.ngModel, function(value) {
$http.get('/rest/isUerExist/' + value).success(function(data) {
//set the validity of the field
$scope.$apply(function(s) {
ctrl.$setValidity('uniqueName', data);
});
});
})
}
}
});
Why it returns "$scope is not defined" message in console??
UPDATE:
If I use"scope." but not "$scope.", then I have different error in the console:
Error: $digest already in progress
Upvotes: 0
Views: 160
Reputation: 13342
Ok. About my second question:
From doc:
$apply() is used to enter Angular execution context from JavaScript
Keep in mind that in most places (controllers, services) $apply has already been called for you by the directive which is handling the event.
So, it makes me think that I do not need: $scope.$apply(function(s) {
Then my code looks like this (and works as expected):
$http.get('/rest/isUerExist/' + value).success(function(data) {
//set the validity of the field
if (data == "true") {
ctrl.$setValidity('uniqueName', false);
} else if (data == "false") {
ctrl.$setValidity('uniqueName', true);
}
});
Upvotes: 0
Reputation: 25159
You've injected it as scope, not $scope. Just change it to scope.$apply
Upvotes: 2