I'm just trying to implement usercheck directive which return user object with success user checking. but i'm unable to bind return object to model once complete user check what was the mistake i have done. my directive as follow
我只是尝试实现usercheck指令,该指令通过成功用户检查返回用户对象。但是一旦完整的用户检查我做了什么错误,我就无法将返回对象绑定到模型。我的指示如下
app.directive('usernameAvailable', function($timeout, $q, $http) {
return {
restrict: 'AE',
require: 'ngModel',
link: function(scope, elm, attr, model) {
model.$asyncValidators.usernameExists = function() {
return $http.get('backend.json').then(function(res){+
$timeout(function(){
var data = res.data;
model.$setValidity('usernameExists', !!data.valid);
model.userModel = res.user;
scope.$apply();
}, 1000);
});
};
}
}
});
Here is the plunker
这是plunker
Thanks
1 个解决方案
#1
1
I fixed your Plunker. Hope this helps... I used .success
instead of .then
and I wrote the user object into the scope.
我修好了你的Plunker。希望这有帮助...我使用.success而不是.then并将用户对象写入范围。
Remark: In this example it is working fine, but it you write a directive with it's own scope the user object wouldn't be visible.
备注:在这个例子中,它工作正常,但是你用它自己的范围编写一个指令,用户对象将不可见。
link: function(scope, elm, attr, modelController) {
modelController.$asyncValidators.usernameExists = function() {
return $http.get('backend.json').success(function(data) {
$timeout(function() {
modelController.$setValidity('usernameExists', !!data.valid);
scope.user = data.user;
}, 1000);
});
};
}
#1
1
I fixed your Plunker. Hope this helps... I used .success
instead of .then
and I wrote the user object into the scope.
我修好了你的Plunker。希望这有帮助...我使用.success而不是.then并将用户对象写入范围。
Remark: In this example it is working fine, but it you write a directive with it's own scope the user object wouldn't be visible.
备注:在这个例子中,它工作正常,但是你用它自己的范围编写一个指令,用户对象将不可见。
link: function(scope, elm, attr, modelController) {
modelController.$asyncValidators.usernameExists = function() {
return $http.get('backend.json').success(function(data) {
$timeout(function() {
modelController.$setValidity('usernameExists', !!data.valid);
scope.user = data.user;
}, 1000);
});
};
}