Vows made in functions, angularjs

I'm trying to figure out how to implement a promise into a function in order to eliminate the use of a timeout. Is this even possible? The function I have is pulling data from a factory called 'Prim' and it looks like this:

$scope.getPre = function(id){

 var url = WEB_API.MainUrl + '/api/prim/' + id +'/' + $window.sessionStorage.getItem('idsom');

    Prim.getprim(function(data) {

        $scope.prim1 = data;
        $scope.prim = $scope.prim1[0];

    }, url); 

    $scope.$apply();

}

Currently, I am using a timeout that I want to remove:

setTimeout(function() { // the function doesn't work without timeout
    $scope.getPre($routeParams.idprim);
}, 100);

Answer №1

To ensure your function returns a promise, you can utilize the .then() method:

$scope.getPre = function(id){
    var deferred = $q.defer()
    var url = WEB_API.MainUrl + '/api/prim/' + id +'/' + $window.sessionStorage.getItem('idsom');

    Prim.getprim(function(data) 
        $scope.prim1 = data;
        $scope.prim = $scope.prim1[0];
        deferred.resolve();
    }, url);

    return deferred.promise;
}

Then, you can execute it like so:

$scope.getPre($routeParams.idprim).then(function () {
    // Perform your tasks here after setTimeout
});

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

Transferring files to Django using AJAX

I am struggling with the process of uploading files to django using ajax. The upload is done within a modal window. The Form <div class="modal fade bs-example-modal-lg" id="fileUploadModal" role="dialog" aria-hidden="true"> <div class="modal ...

Can you provide guidance on transforming a JSON date format like '/Date(1388412591038)/' into a standard date format such as '12-30-2013'?

I have a json that is created on the client side and then sent to the server. However, I am facing an issue with the conversion of the StartDate and EndDate values. Can someone please assist me with this? [ { "GoalTitle": "Achievement Goal", ...

Trying to dynamically filter table cells in real time using HTML and jQuery

During my search on Stack Overflow, I successfully implemented a real-time row filtering feature. However, I now require more specificity in my filtering process. Currently, the code I am using is as follows: HTML: <input type="text" id="search" place ...

An issue related to AngularJS and the injection of ui-bootstrap components has been encountered

I'm encountering an issue with injection errors in my code, and unfortunately, the debugger in Firefox isn't providing much help. Here are snippets of the code: This is the Controller file causing the error: App.controller('ModalInstanceCt ...

Warning: [ng:areq] The function called in the MainController is not defined and resulted in an error. Visit http://errors.angularjs.org/1.3.15/ng/areq?p0=MainController&p1=not%20a%20function%

When creating unit tests for my controller, I encountered the following error: Error: [ng:areq] http://errors.angularjs.org/1.3.15/ng/areq?p0=MainContr oller&p1=not%20a%20function%2C%20got%20undefined I'm unable to find the cause of this iss ...

Filtering a list by name in AngularJS is a simple task that can be accomplished using

I'm in need of setting up a search filter based on name only. I don't have much experience with angularjs, so any guidance would be appreciated. Here's what I have so far, but it requires some modifications: <input type="text" ng-model=" ...

AngularJs, Dynamically Adjusting URL Parameters Based on User Input

I am currently working on integrating my ASP.NET Web API with AngularJs. I am facing an issue where I need to pass optional parameters to the URL based on user input from 2 HTML text boxes, but I am unsure of how to accomplish this. Below is a snippet of ...

Is it possible to extract information from a string with regular expressions?

As I sift through a myriad of arbitrary "Header" data in node. Here's an example of what it looks like: _Aa:GA1.1.78037747.867108, 44907=5xyz; Webstorm-a36041d5=9fbb-48e9-b19e-e3f0a3282151; srce=coolernode; nsid=1234; cookie_data=T%3D1; _gat_PP= ...

Creating a list in Angular.js using the ng-repeat directive to iterate through data from

Recently, I started my journey with Angular.js and encountered my first small hurdle. This snippet is from my hello.js file: function Hello($scope, $http) { $http.get('URL'). success(function(data) { $scope.response = data });} The resp ...

Can a plugin be executed as a test?

I am currently using HTMLhint, however, I would like to have it run as a test rather than just through the command line plugin. Is there a way to achieve this and if so, how can I do it? I have searched online but haven't been able to find a solution ...

Tips for running two elixir tasks consecutively?

Check out this piece of code: var gulp = require('gulp'), fs = require('fs'); gulp.task('taskOne', function() { return gulp.src('folder1/file1.js') .pipe(gulp.dest('folder2')); }); gulp.t ...

Chat lines in Chrome displaying double entries - troubleshooting needed

I developed a chat plugin for my website with a simple HTML structure: <div id="div_chat"> <ul id="ul_chat"> </ul> </div> <div id="div_inputchatline"> <input type="text" id="input_chatline" name="input_chatline" val ...

Using Promises to transmit a variety of request outcomes

Looking to create an express server that can fetch data from an array of items? Take a look at this helpful question, which suggests using Promise.each for the task... The objective is to: Scrape a web page containing a list of movies and extract their ...

Template for recursive tree structure with ng-click function utilizing a multidimensional index as a parameter

Good evening, I am interested in creating a template that can recursively display a structured list with an onclick function on each item. The onclick function should provide the full index of the current element, including all parent indexes (e.g. [0][2] ...

Resetting the form and validation in AngularJS post form submission

I need help resetting a form and all validation messages after submission. Check out my code on plunker: http://plnkr.co/edit/992RP8gemIjgc3KxzLvQ?p=preview Here is the code snippet: Controller: app.controller('MainCtrl', function($scope) { ...

Creating Bound HTML inside an AngularJS Grid Cell Template

I recently started using angular js and came across a helpful question on Conditional cell template in ui-grid angularjs. It worked perfectly for me, but now I'm curious about how to display HTML elements like a button tag instead of plain text. Whene ...

Show just a single error message if there are two validation errors present

In my AngularJS timepicker, users can choose multiple time segments for each day. The code has validation to detect duplicates and overlapping time segments. For example, entering 11:00am - 12:00am twice will trigger two error messages: 'Overlapping t ...

Resolving issues with jQuery's live() method while incorporating AJAX calls

One of the challenges I'm facing is with buttons on a webpage that are part of the class "go". The code snippet below demonstrates how I handle actions related to these buttons: $(".go").live('click', this.handleAction); The issue arises w ...

What causes the updated value to be appended to an array when using the spread operator to modify an existing property's value?

In my state, I have an array of objects: const initialState=[{a:1},{b:2},{c:{d:3}}] const [state,setState]=useState(initialState) My goal is to modify the value of b to 5 within my event handler: function changeBToFive() { setState((state) => [ ...

The blending of Laravel and AngularJS for a powerful development strategy

As I embark on my journey to learn AngularJS, I decided to create a simple app to put my knowledge to the test. Although my app is not a traditional Single Page Application (SPA), as the login process is handled by Laravel before redirecting users to the ...