Using the promise expression in AngularJS's ng-show

I have a scenario where I am using ng-show with an expression that evaluates to a promise which then resolves to a boolean. This setup is resulting in a 10 digest iterations overflow error.

For reference, you can view the code snippet at http://plnkr.co/edit/XibYM0kCnXhKjNUeTsp3?p=preview

  <body ng-controller="MainCtrl">
    <p ng-show="returnsABoolean()">non promise</p>
    <p ng-show="returnsAPromiseThatResolvesToABoolean()">promise</p>
  </body>

Controller:

  $scope.returnsABoolean = ()->
    true

  $scope.returnsAPromiseThatResolvesToABoolean = ()->
    $q.when(false)

While I am confident that {{somePromise}} will resolve successfully, the issue seems to arise with

{{returnsAPromiseThatResolvesToABoolean()}}
.

Any suggestions on how to resolve this? I was expecting this implementation to function as intended..

Answer №1

Automatically, AngularJS handles resolving promises for template binding. It is recommended to utilize the promise within ng-init to avoid triggering a new promise during every digest cycle.

<p ng-init="v=checkIfPromiseResolved()" ng-show="v">resolved promise</p>

Answer №2

Check out this Plunker demo: http://plnkr.co/edit/NvjP5qHafhyIWXXotBej?p=preview

The code appears to be functioning as desired. The $q.when() method is returning a promise object, rather than a boolean value, which is then passed to ng-show.

Here is the updated template:

  <body ng-controller="MainCtrl">
    <p ng-show="returnsABoolean()">non promise</p>
    <p ng-show="returnsAPromiseThatResolvesToABoolean">promise</p>
  </body>

And the updated controller:

  $scope.returnsABoolean = ()->
    true

  promise = $q.when(false)
  promise.then((val) ->
    $scope.returnsAPromiseThatResolvesToABoolean = val)

Answer №3

If you take a look at the resources linked here, you will notice that the promise is resolved in the next available tick, causing the $scope to only update during the next angular $digest cycle. However, your function is generating a new promise with each $digest cycle, never waiting for the previous promise to resolve.

This is a known issue that has been previously discussed here.

To resolve this problem, you can maintain a persistent reference to your promise outside of the function, like I have demonstrated here.

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

Does __ only function with curried functions as intended? What is the reason for it working in this case?

I'm trying to figure out the reason behind the successful usage of __ in this particular code snippet : function editAddress (id, addressId, model) { return BusinessService .getById(id) .then(unless( () => checkUrlValue(add ...

The importance of understanding Req.Body in NODE.JS POST Requests

Currently, I am developing a Node.JS application that interacts with a MySQL database. The app retrieves data from the database and displays it in a table using app.get, which functions correctly. The issue I am facing is that when utilizing app.post, re ...

Troubleshooting a CORS problem with connecting an Angular application to a Node server that is accessing the Spotify

I am currently working on setting up an authentication flow using the Spotify API. In this setup, my Angular application is making calls to my Node server which is running on localhost:3000. export class SpotifyService { private apiRoot = 'http://lo ...

Why is this component not functioning properly?

I am struggling with making a function to add a component dynamically when I click a button, similar to the code below. However, my attempt at creating a separate method for adding the component instead of using an inline expression is not working. Can som ...

Using a variable in Ajax URL with Action razor syntax

I have a function that calls a method in the controller through an Action URL. However, I need to use a parameter as the name of the method, but unfortunately, this is not possible in the current implementation. function changeDropDownList(id, dropNameToC ...

Display recommendations as soon as a specific character is entered in the text box

Issue Description: I am looking to implement a specific feature using Javascript or JQuery. When a user types a designated character, such as the @ symbol, in a text box, I would like the values of an array to be displayed in a drop-down menu. For example, ...

Navigating the world of cryptocurrency can be daunting, but with the right tools

Hello fellow developers, I've encountered some difficulties with cryptocurrency in my Nativescript project. I am attempting to incorporate the NPM package ripple-lib into my code, but I have been unsuccessful using nativescript-nodeify. How can I suc ...

Searching through a JSON object for nested objects within objects

Currently, I have some data structured as follows: var items = [ { "id" : 1, "title" : "this", "groups" : [ {"id" : 1, "name" : "groupA"}, {"id" : 2, "name" : "groupB"} ] }, { "id" : 2, "title" : "that", ...

The prop observation was activated without any alterations

Within my component, I have a prop X that I assign to data Y during the created hook. This setup allows me to easily modify Y without affecting X. Both X and Y are Arrays. Additionally, I've set up a watch on prop X to ensure Y is updated whenever X ...

producing a NaN result when calling a reducer with an integer value

Could anyone assist me with this react-redux code? I have an input field that accepts numbers and adds them to the counter above. My goal is to reset the counter to 0 if the input is not a number, but currently when I type any character other than an int ...

What is the proper way to safely escape a JSON string for an object that contains user-generated content?

How can I correctly use the variable s for the value-field of an option-element while escaping user input used for key and value? var key='highway'; var value='track'; var s = JSON.stringfy({ [key]:value }, undefined,''); s ...

"Encountering a 404 error when submitting a contact form in Angular JS

Looking to set up a contact form for sending emails with messages. Currently diving into Angular Express Node Check out the controller code below: 'use strict'; /** * @ngdoc function * @name exampleApp.controller:ContactUsCtrl * @descripti ...

Customize the filename and Task Bar name for your Electron app when using electron-packager

My application uses electron packager to build the app on Mac. Here is my package.json configuration: { "name": "desktop_v2" "productName": "desktop v2", "version": "1.0.0", "license": "MIT", "scripts": { "build": "node --max_o ...

What are the steps to generate an npm package along with definition files?

Is it possible to create an NPM package with definition files containing only interfaces declared in *.ts files? Consider a scenario where we have two interfaces and one class definition: export interface A { id: number; } export interface B { name: s ...

Executing a callback in AngularJS after multiple HTTP requests have been completed using a forEach loop

I am trying to update multiple items within a foreach loop by sending HTTP requests, and I need a callback once all the requests are complete. Despite searching on Stack Overflow, I haven't found a solution that works for me. Here is the snippet of m ...

Verify the dialog box return with a text input box

I am trying to implement a confirmation dialog box for when a user wants to delete their account. This dialog box requires the user to enter their password in a textbox. However, I am struggling with catching the postback event and executing the relevant m ...

I am looking to create a password generator that saves all generated options to a file

I am looking to create a custom password generator that writes all generated options to a file. For example, using the numbers "0123456789" and having a password length of 3 characters. However, I am facing an issue with the file writing process where it ...

Troubleshooting the Width Problem in Bootstrap 5 Dropdowns

I am currently working on a new project and encountering an issue with the width of a Bootstrap 5 dropdown. The problem lies in the discrepancy between the button width and the menu width. Although it may seem simple, I am having trouble resolving it as I ...

Are you transitioning from traditional scroll pagination to using ajax?

Is it possible to replace scroll pagination with ajax? I'm looking for an alternative to the large scroll pagination query and wondering if ajax could be used instead. Here is the current code snippet: feeds.scrollFeedPagination({ 'contentPage ...

JavaScript enables the deletion of a class

In HTML 2, I am able to show different statements based on the scenario. These statements are styled using the Bootstrap alert class. The goal is to ensure that when new data is sent, any old communication disappears without causing overload on the page. ...