Passing a value back to a template from a promise

Currently, I am implementing server-side validation for dynamically created input fields within div tags. The issue I am facing is that I need to display the API error message in my template instead of directly setting it in my controller. If I set it in the controller, it will impact all input fields.

My approach is to implement something like the following:

#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;

};

This code is just a simplified example and may be missing some unimportant details.

My question is, how can I effectively return the promise data to be displayed in my template?

Answer №1

With promises, you don't simply "return" data. Instead, you fulfill promises by providing data. Make sure to trigger promise.resolve(data) in order to send the data to your callback functions.

Answer №2

When working with Angular, you can easily display a model from the $scope if 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>

However, this method can sometimes lead to recursive and potentially infinite $apply calls. A safer approach would be to display a subset of each item in the array.

<span ng-repeat="item in items">{{item.asyncResult}}</span>

For asynchronous loading of each item, you can use the following technique:

$timeout(function () {
  angular.forEach($scope.items, function (item, idx) {
    item.asyncResult = 'done with ' + idx + ' !';
  });
}, 3000);

When dealing with multiple inputs sharing the same name in a form, since Angular does not support dynamic names for form inputs, consider using nested ng-form elements with the same name. For more information, refer to this question.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilizing AngularJS: Conditionally rendering ngIf within an array of objects containing unique properties

Facing a challenge with the ngIf directive that I have been struggling to resolve despite trying various solutions. In my scenario, I have an array of objects, each containing different properties. The structure is as follows: object = [ { ...

Steps for aligning an image and text within an icon next to each other

I'm looking to align a small PNG image next to some text within an icon. How can I achieve this? Currently, they are stacked vertically. Here is the current layout - I want the two elements side by side instead. The structure of the division is unique ...

Building paths through a jQuery loop

Transform String into Delimited Array, Generate Loop of Check Boxes, and Build New String Given String = "Folder Tier1\Folder Tier2\Folder Tier3\Folder Tier4\Folder Tier5\Folder Tier6\" (Missing) Use "\" as a delimi ...

AngularJS Drop-Down Menu

Having trouble with a select box in AngularJS. Obtaining the locationList like this: locationFactory.getLocation().then(function (data) { $scope.locationList = data.data.locationList; }); Result can be seen here: Result This is how it is ad ...

Adjusting the layout of tables for an accordion design

I am facing an issue with displaying the accordion in a table layout. When I expand them, the arrangement gets disrupted. To see the table layout for the accordion, you can check it here. <div ng-controller="AccordionDemoCtrl"> <label class="che ...

What is the best method to extract an array of values or rows from my grid layout?

Looking for a way to convert my CSS-grid into a CSV format. I came across a helpful thread outlining how to structure the data in an array: How to export JavaScript array info to csv (on client side)?. Is there a method to extract all the div values in th ...

Replace .Mui-disabled (or any other pseudo-classes/states) in the MUI v4.1.X theme with custom styling

How can I globally override the default grey background color for disabled items in Material-UI v4.1.x? I know how to do it for specific components like MuiMenuItem, but I'd prefer a solution that doesn't require me to add overrides for each indi ...

The ng module instantiation failed because of an error related to an unresolved dependency for $logProvider. More information can be found at http://errors.angularjs.org/undefined/$injector/unpr?p0=%24log

I have created this code snippet to enhance the $log functionality: window.fofr = window.fofr || {}; window.fofr.library = window.fofr.library || {}; window.fofr.library.logging = window.fofr.library.logging || {}; window.fofr.library.logging.errorLo ...

HTML control for adjusting the pan and tilt of a device

I'm looking to develop an interactive input where users can drag a dot within a box and see the 2D coordinates of that dot displayed. The goal is to use this feature to control pan and tilt values. A similar functionality from another application is s ...

Resizing and uploading multiple images with accompanying descriptions

I am in need of a solution for uploading multiple images along with descriptions. Users will be uploading 1-10 large-sized images from cameras, so it would be ideal if the images could be resized before the upload. My requirements are: Compatibility wit ...

Error in canvas-sketch: "THREE.ParametricGeometry has been relocated to /examples/jsm/geometries/ParametricGeometry.js"

I recently started using canvas-sketch to create some exciting Three.js content. For my Three.js template, I utilized the following command: canvas-sketch --new --template=three --open The version that got installed is 1.11.14 canvas-sketch -v When atte ...

Passing variables dynamically in a created Express.js route

Creating routes in Express.js from a JSON file with the specified structure: { "/home":{ "token":"ksdjfglkas" }, "/logout":{ "token":"ksdjfglksaudhf" } } It is necessary to access the token within the routes function. The JavaScript code ...

Finding the index of a column based on a continuous sequence of values can be achieved by following these

Consider this sequence of numbers representing components on a page: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 Every set of 3 numbers makes up a page, with indexing restarting for each new page. Essentially, it follo ...

What does it mean in Javascript when b1 is undefined while o1 has a value and is equal to b1?

Having some issues getting variables to work with drop down options on a page. At first, I couldn't even extract a value from the function but managed to do so by removing "var" from o1. Strange thing is, when I type o1 into the js console on chrome i ...

Using document.getElementById will only target a single item

Essentially, I am facing an issue where the document.getElementById() function only works for the first product when I click on the addToBasket button. It always changes the details of the first product, even if I click on a different one. Is there a way ...

Switch out the name of multiple elements with mootools

Is there a Moo tool that can replace multiple element IDs? I currently have the following code: $$('myelement').each(function(el){ var get_all_labels = el.getElements('label'); var get_label_id = get_all_l ...

What is the best way to reference an ImageButton using jquery?

I created an HTML page with a special div in the body that contains a collection of buttons and images. <div id="div_one"> <button id="button_one"> <asp:Image id="image_button_one" ImageUrl=".." runat="server"> </button> </div& ...

Please indicate the number of lines for the href within the span element

I'm struggling with formatting a <span> tag, specifically the .lastMessageLink class that contains an <a> element with the .lastMessageText class. The content within .lastMessageText can vary from just a few characters to a lengthy paragra ...

What causes errors in URL routeProvider with AngularJS?

Implementing routeProvider in Angular JS allows me to structure my links like this: www.site.com/profile#/profile/profession/3 However, when trying to access the page, Angular JS displays the following error message: Uncaught Error: Syntax error, unreco ...

Intellij IDEA does not offer auto-completion for TypeScript .d.ts definitions when a function with a callback parameter is used

I've been working on setting up .d.ts definitions for a JavaScript project in order to enable auto-completion in Intellij IDEA. Here is an example of the JavaScript code I'm currently defining: var testObj = { tests: function (it) { ...