"Trouble with AngularJS Array Loading: View doesn't show data upon load, but alerts and console

I'm facing an issue where I'm trying to populate an array with values, but it keeps showing up as empty. Oddly enough, the alerts are working correctly. It seems like I might be overlooking something obvious here. Any insights or suggestions on what might be causing this? Below, you'll find the code snippet where I attempt to push values into the array along with another section of code that includes working alerts.

    $scope.termsArray = [];

    execOperation();

    function execOperation() {
        //Current Context
        var context = SP.ClientContext.get_current();
        //Current Taxonomy Session
        var taxSession = SP.Taxonomy.TaxonomySession.getTaxonomySession(context);
        //Term Stores
        var termStores = taxSession.get_termStores();
        //Name of the Term Store from which to get the Terms.
        var termStore = termStores.getByName("Taxonomy_111111111111");
        //GUID of Term Set from which to get the Terms.
        var termSet = termStore.getTermSet("12345-55-689");
        var terms = termSet.getAllTerms();
        context.load(terms);
        context.executeQueryAsync(function () {
            var termEnumerator = terms.getEnumerator();
            while (termEnumerator.moveNext()) {
                var currentTerm = termEnumerator.get_current();
                $scope.termsArray.push({
                                termName: currentTerm.get_name(),
                                termGUID: currentTerm.get_id(),
                                termSynonyms: 'Coming Soon'
                            });
            }

        }, function (sender, args) {
            console.log(args.get_message());
        });

    }

Check out the following code block where everything is working with alerts:

function execOperation() {
        //Current Context
        var context = SP.ClientContext.get_current();
        //Current Taxonomy Session
        var taxSession = SP.Taxonomy.TaxonomySession.getTaxonomySession(context);
        //Term Stores
        var termStores = taxSession.get_termStores();
        //Name of the Term Store from which to get the Terms.
        var termStore = termStores.getByName("Taxonomy_111111111111");
        //GUID of Term Set from which to get the Terms.
        var termSet = termStore.getTermSet("12345-55-689");
        var terms = termSet.getAllTerms();
        context.load(terms);
        context.executeQueryAsync(function () {
            var termEnumerator = terms.getEnumerator();
            var termList = "Terms: \n";
            while (termEnumerator.moveNext()) {
                var currentTerm = termEnumerator.get_current();
                $scope.termsArray.push({
                    termName: currentTerm.get_name(),
                    termGUID: currentTerm.get_id(),
                    termSynonyms: 'Coming Soon'
                });

                termList += currentTerm.get_id() + currentTerm.get_name() + "\n";
            }
            alert(termList);
        }, function (sender, args) {
            console.log(args.get_message());
        });
    }

Here's the HTML output:

<div> {{termsArray}}</div>

Currently, it returns []

Update: An interesting observation is that if I click on an input box and then navigate away, or interact with an alert and dismiss it, the array loads successfully instead of on page load.

Answer №1

After digging into this issue, I discovered that Angular doesn't properly handle non-Angular functions during the loading process. As a workaround, I had to encapsulate the $scoped array within a $scope.apply function. For more information, you can refer to this link: Execute SharePoint Function On Page Load in AngularJS Application ($scope issue???)

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

Integrating data binding within a .append function using AngularJS

I followed this code example (http://jsfiddle.net/ftfish/KyEr3/) to develop a form. However, I encountered an issue with an input having ng-model set to "value" and needing to display that value within {{ }} in a TD: angular.element(document.getElementByI ...

Is it possible to iterate through an object with multiple parameters in Op.op sequelize?

Currently, I am in the process of setting up a search API that will be able to query for specific parameters such as id, type, originCity, destinationCity, departureDate, reason, accommodation, approvalStatus, and potentially more in the future. const opt ...

Having a slight hiccup with pixel alignment and browser compatibility in my jQuery animation

To emphasize a specific paragraph element, I developed a JavaScript function that displays it above a darkened background. My approach involved using jQuery to generate an overlay and then duplicating the targeted paragraph element while positioning it ab ...

What is the most effective method for comparing two arrays of objects and extracting the differing values within a React application?

I am currently working on implementing a changelog feature for my website. Let's consider the initial array as initArray: [ { "id": 1, "val1": "2023-08-28", "val2": 1, " ...

insert a new DOM element into an array using jQuery

Looking at the code snippet below: a_ajouter = $('.question'); hidden_div.push(a_ajouter); console.log(hidden_div); Upon examining the output in the console, instead of a DOM object being added to the div as intended, it shows &apo ...

The JavaScript error occurred: TypeError - Unable to access the property 'map' as it is undefined

import Link from 'next/link' export const getStaticProps = async () => { const res = await fetch('https://jsonplaceholder.typicode.com/users'); const data = await res.json(); return { props: { ninjas: data } } } const ...

Is there a way to track when the Angular DTOptionsBuilder ajax call is complete and trigger a callback function?

Working with angular datatables, I have the following code: beforeSend:</p> success callback causes the table on the page not to populate with the data. How can I implement a callback that triggers once the ajax is done without interfering with the ...

Using Vue to bring in an npm module that does not have any exports

I'm facing a challenge when trying to bring in an npm package into a Vue component. This package (JSPrintManager - here) consists of a JavaScript file with no exports. Therefore, I'm unable to utilize the following import statements: import { J ...

Utilizing Async / Await in the created lifecycle hook - Vue2

I recently installed the vue-element-loading package and added its component to my page.vue: <vue-element-loading :active="isActive" :is-full-screen="true"/> After adding a variable to my data: data () { return { isActive: false, } } I th ...

The Evolution of Bulma's Navigation Menu

Creating a transparent menu in Bulma has been successful for the desktop viewport: VIEW DESKTOP MENU However, when attempting to implement the same design on mobile, the menu ends up like this: VIEW MOBILE/TABLET MENU The mobile version seems to inheri ...

Utilizing dynamic jQuery events with variable integration

I'm having some trouble incorporating a variable into a dynamically added jQuery event. Every time I click, the message displayed is "The number is 3" for all div elements. $( document ).ready(function() { for (var i = 0; i < 3; i++) { ...

Angular directives for Kendo UI

I have been working with Angular 1.5.* in conjunction with Kendo UI. I have followed all the steps outlined in the documentation on the Telerik site, including: Ensuring that the kendo scripts and styles are included Adding kendo.directives to my angular ...

Focusing on particular jQuery elements that share the same class names

I am facing an issue with dynamically generated divs that share the same class names. When I hover over the parent div (myDiv), I want to trigger an event and add a class to the myDiv child button. However, when I click on the parent div, I want to unbind ...

Convert currency into words using a JavaScript function

After searching for scripts to format currency in Portuguese, I came across several options that were tailored for ENG/US currency. Adapting them to meet my needs proved to be quite challenging. Even when attempting to modify a script myself, I encountere ...

Obtain user input dynamically rather than statically assigning values in an array

Is there a way to retrieve user input from a form using jQuery and add it to a PHP array for a Wordpress query? Specifically, I want to replace the hardcoded value '123456' in the PHP array with the value stored in a variable generated by my jQue ...

The parseFloat function only considers numbers before the decimal point and disregards

I need my function to properly format a number or string into a decimal number with X amount of digits after the decimal point. The issue I'm facing is that when I pass 3.0004 to my function, it returns 3. After reviewing the documentation, I realized ...

angucomplete-alt: retrieving text value in case of no matches

Using Angucomplete-alt has been effective for me when I want to guide users into selecting from a pre-defined list of options. However, what if I want to allow users to enter free text and only provide suggestions as completions, rather than mandating a s ...

Sending a list of data using ajax to an external PHP script for deferred rendering in datatables

I've set up a form on one of my pages that features check boxes linked to the primary id of certain information that is retrieved on another page based on whether the check box was checked or not. After switching to jquery-datatables with deferred ren ...

Checking for "in array" using AngularJS expressions

I need a clean and efficient way to achieve something like the following: <span x-ng-show="stuff && stuff.id in [1,2,5]">{{stuff.name}}</span> <span x-ng-show="stuff && stuff.id in [3,4,6]">{{stuff.fullName}}</span> ...

What is the best way to showcase current elements using Vue.js and firebase without them being outdated?

When working with Firebase, I was able to successfully retrieve and print out a list of events. However, now I'm facing a challenge - I want to load only the "Events" that are not outdated. Any suggestions or tips on how to achieve this? I'd grea ...