Reputation: 1206
Iam doing serverside validation in dynamicly created input fields that resides within tags. Problem is that I need to return the API error message back to my template, not set it directly in my controller. If I set it in my controller it will affect all input fields.
My plan is to do something like this:
#Template
..<span ng-show="innerNameForm.name.$error.apiResponse">{{ msg }}</span>
..<input type="text" ng-change="msg = someFunction(inputValue, innerNameForm)"...... />
#Controller
scope.someFunction = function(value, form){
apiMsg = timeout(function() {
var prom = vcRecordValidate.name(value, record_id).then(function(promise){
//If fails... do this
form.name.$setValidity('apiResponse', false);...
return promise; //THis contains the API error message
});
return prom;
}, 1000);
return apiMsg;
};
Code is just an example, and is missing some unimportant stuff..
Upvotes: 2
Views: 278
Reputation: 1696
Angular supports the display of a model from the $scope
when it's a promise
.
$scope.load = function (i) {
var deferred = $q.defer();
$timeout(function () {
deferred.resolve('done with ' + i + ' !');
}, 3000);
return deferred.promise;
}
...
<span ng-repeat="item in items">{{load($index)}}</span>
But this can be tricky and generate recursive and maybe infinite $apply
calls. If I were you I would just display a subvar of every item in my array
<span ng-repeat="item in items">{{item.asyncResult}}</span>
and asynchronously trigger the load of every item like this for instance
$timeout(function () {
angular.forEach($scope.items, function (item, idx) {
item.asyncResult = 'done with ' + idx + ' !';
});
}, 3000);
And to deal with multiple inputs with the same name inside a given form, since Angular does not support dynamic names for form inputs, I would suggest you to use nested ng-form
with the same name (see this question for details).
Upvotes: 0
Reputation: 239302
You don't "return" data through promises. You fulfil promises with data. You need to invoke promise.resolve(data)
to pass data
to your callbacks.
Upvotes: 1