Async ngInit does not function properly when using $q promises

Edit: Plunker seems to be working fine, but the actual code is not functioning as expected. You can check it out here: http://plnkr.co/edit/5oVWGCVeuTwTARhZDVMl?p=preview

The service contains the usual getter\setter methods and works well. I have omitted posting its code to keep things concise.

To summarize: I am attempting to initialize a value fetched via AJAX into the ngModel of a text-area using ng-init. Though the request returns the correct value, the textarea remains empty.

Here is the function in the parent controller that communicates with the service:

$scope.model.getRandomStatus = function(){
    var deffered = $q.defer();
var cid = authService.getCompanyId();

var suggestions = companyService.getStatusSuggestions(cid);
if(suggestions && suggestions.length > 0){
        deffered.resolve(suggestions[Math.floor(Math.random(suggestions.length) + 1)].message);
        return deffered.promise;//we already have a status text, great!
    }

    //no status, we'll have to load the status choices from the API
    companyService.loadStatusSuggestions(cid).then(function(data){
        companyService.setStatusSuggestions(cid, data.data);
        var result = data.data[Math.floor(Math.random(data.data.length) + 1)];
        deffered.resolve(result.message);   
    },
    function(data){
        _root.inProgress = false;
        deffered.resolve('');
        //failed to fetch suggestions, will try again the next time the compnay data is reuqired
    });
    return deffered.promise;
}

This is the function in the child controller:

.controller('shareCtrl', function($scope){
    $scope.layout.toggleStatusSuggestion = function(){
         $scope.model.getRandomStatus().then(function(data){
            console.log(data);//logs out the correct text
            //$scope.model.formData.shareStatus = data;//also tried this, no luck
            return data.message;
         });
    $scope.model.formData.shareStatus = $scope.layout.toggleStatusSuggestion();//Newly edited
    }
});

Below is the HTML snippet:

<div class="shareContainer" data-ng-controller="shareCtrl">
 <textarea class="textAreaExtend" name="shareStatus" data-ng-model="model.formData.shareStatus" data-ng-init="model.formData.shareStatus = layout.toggleStatusSuggestion()" cols="4"></textarea>
</div>

Answer №1

It seems like you are looking for this solution :

$scope.model.getRandomStatus().then(function(data){            
            $scope.model.formData.shareStatus = data.message;

});

If you return something from inside the then function, it will not affect the outer function and will essentially do nothing.

Answer №2

It came to light that a personalized validation directive was actively monitoring modifications in the model using $formatters, restricting it to 80 characters (like Twitter). Surprisingly, it was failing quietly because I hadn't anticipated inserting invalid values into my forms programmatically - a foolish oversight that could catch anyone off guard. I had to tweak the directive to address this issue, serving as a valuable lesson for others who may encounter the same situation.

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

Learn the process of dynamically populating an HTML table with data using JavaScript and JSON

I have developed a code snippet to dynamically add an HTML table without using jQuery. The code serves as an application from the server to the client, where the client receives a JSON object to parse into a string. Here is how you can add an HTML table ...

Angular modules are designed to repeat chunks of code in a

Whenever I scroll the page, my function pushes items to an array. However, I am facing an issue where the pushed items are repeating instead of adding new ones. Solution Attempt onScroll(): void { console.log('scrolled'); var i,j,newA ...

The users in my system are definitely present, however, I am getting an error that

Whenever I attempt to retrieve all the post.user.name, an error is displayed stating Cannot read properties of undefined (reading 'name') I simply want to display all the users in my node Even though user is not null, when I write post.user, i ...

How to unselect a radio button in Vue using a button, similar to using vanilla JavaScript

Looking to translate this vanilla JavaScript code into Vue, here's the original: const radio = document.querySelector('#radio'); const boton = document.querySelector('#boton'); boton.addEventListener('click', () => { ...

React eliminates all white spaces

Presented here is a compilation of various span elements: <span>1</span> <span>2</span> <span>3</span> <span>4</span> <span>5</span> Accompanied by the CSS style for these elements: span{ bac ...

Unclear outcomes from iterative loops

I have a question about this particular for loop: for (var i=0,j=0;i<4,j<20;i++,j++) { a=i+j; } console.log(a); Can someone explain why the output is 38? I initially expected it to be 6. ...

What is the best way to send a JavaScript array to a Perl script using AJAX?

Is it possible to convert a JavaScript array passed via AJAX into a Perl array? Accessing in Perl: @searchType = $cgi->param('searchType'); print @searchType[0]; Result: employee,admin,users,accounts It appears that the first value in the ...

What is the best way to retrieve the value of the 'body' object from a Slim_Http_Request Object?

Within my angular application, I have implemented the slim framework as a server. I am facing an issue capturing the body value from the Slim_Http_Request Object. Here is a snippet of my app.js code: MyApp.controller('Remove', function($scope,$ ...

Creating an automated sequence of $http requests to sequentially retrieve JSON files with numbered filenames in Angular 1.2

I have a series of JSON files (page1.json, page2.json, etc.) that store the layout details for our website pages. Initially, I would load each page's data as needed and everything was functioning smoothly. However, it is now necessary for all page da ...

What is the best way to set up a session using jQuery?

I've been troubleshooting my code and I can't seem to figure out why the jquery.session.js file isn't working. Can someone help me find a solution? $.session.set('rmng_time', remaining_seconds); alert("j session "+$.sessi ...

When Ajax sends an HTTP Get request to an MVC Controller with a complex JSON object as a parameter, the controller receives it as null

I am currently working with three classes: public class MainSearch { public MainSearch() { SearchData searchData = new SearchData(); SearchMode searchMode = new SearchMode(); } public SearchData searchData { get; set; } ...

A Guide to Utilizing Parameters in Javascript Strings

I'm in search of a solution but struggling to find a comprehensive explanation. I am working on a code where I need the flexibility to easily update strings or other parameters. What I aim for is passing values to a string when calling it through a ...

Manage shared nested modules across different modules in Vuex without redundancy

In my Vue.js application, I am using Vuex as the state manager. To ensure that certain states are shared across different components, I have created a nested state containing all the common information. This allows me to import it into multiple modules. F ...

When programming with PHP and JavaScript, managing events' start dates and end dates

In my current project, I am developing a script that deals with events. An event is scheduled to start on 12/02/2016 at 11:20 and end on 01/04/2016 at 8:20. When the end date is reached, I need to trigger a specific action using JavaScript. if (t.getFullY ...

Maximizing the potential of JavaScript by utilizing effective tags

Looking to enhance my JavaScript code by adding a maximum tags option limited to 6 with no duplicates. Check out the current snippet below: <div id="tags"> <span>php</span> <span>c++< ...

Upcoming API and backend developments

When working with the NEXT project, API Routes provide the ability to create an API endpoint within a Next.js application. This can be achieved by creating a function in the pages/api directory following this format: // req = HTTP incoming message, res = H ...

I'm looking for a way to retrieve an object from a select element using AngularJS. Can

I am working with a select HTML element that looks like this: <select required="" ng-model="studentGroup"> <option value="" selected="">--select group--</option> <option value="1">java 15-1</option> <option value="2">ja ...

What are the best ways to utilize angular's ng-repeat or ng-options?

Facing an issue here. Trying to display a list of options in a select element from a service. The service is returning an array with the following values: ["AZERBAIDJAN", "BRAZIL", "CAMEROON", "EQUATOR", "FRANCE", "GHANA"] I'm undecided on whether t ...

Store the beginning and ending times in a MySQL database using Sequelize and Node.js

I am currently developing a project management application where I need to keep track of the start and stop time for user work. To achieve this, I have implemented two buttons in the UI - START and STOP. When a user clicks the START button, the following ...

Manipulate input fields dynamically with JavaScript

I am currently working on a functionality that involves generating an alert button based on a selection from a drop-down menu. The JavaScript part of the code is able to successfully read and send the values from the <select> drop-down as intended. H ...