ngOptions failing to reflect changes when new objects are added to array

I am facing an issue with updating the view when a new object is pushed to an array that contains objects. It seems like the problem lies with $scope.$apply, but I'm not sure how to implement it properly. I attempted wrapping the push function in $scope.$apply, but the error message shows that $scope is undefined.

View:

        <label for="groupOwner">List Template:
            <select 
                id="listTemplate"
                ng-model="newList.template"
                ng-options="t.name for t in listTemplates|orderBy: 'name'"
            ></select>
        </label>

Ctrl:

    $scope.createList = function (){
        var modalForm = '/Style%20Library/projects/spDash/app/partials/newList.html';   
        var modalInstance = $modal.open({
            templateUrl: modalForm,
            backdrop: true,
            windowClass: 'modal',
            controller: 'newListCtrl',
            resolve: {
                newListData: function (){
                    return $scope.newList;
                }
            }
        });

        modalInstance.result.then(function(newList){
            SiteService.createList(newList,$scope.site);
        });
    };

Service function:

var createList = function (newList, site){
    var promise = $().SPServices({
        operation: "AddList",
        webURL: site.url,
        listName: newList.name,
        description: newList.description,
        templateID: newList.template.id
    })

    promise.then(function (){
        addToQuickLaunch(newList.name,site.url)
        getSiteInfo(site);
        //take new list object and push to siteLists array
        siteLists.push(newList);
    },function (reason){
        console.log('Failed: ' + reason);
    })
}  

function addToQuickLaunch (name,siteUrl) {
    $().SPServices({
      operation: "UpdateList",
      webURL: siteUrl,
      listName: name,
      listProperties: "<List OnQuickLaunch='TRUE' EnableVersioning='TRUE'/>",
      completefunc: function(xData,Status){
        console.log(name + " list created")
      }
    });
}

Answer №1

This particular piece of code immediately catches my attention:

modalInstance.result.then(function(newList){
    SiteService.createList(newList,$scope.site);
});

It's not ideal to pass the array from the controller to the service in this manner. A better approach would be:

modalInstance.result.then(function(newList){
    return SiteService.createList(newList);
}).then(function(list) {
  $scope.site.lists.push(list);
});

In this scenario, the createList function will return a promise, and that promise will resolve with the object intended for addition to $scope.site.lists. However, it's important to remember that having too much logic in the controller is not recommended. To improve this, create a single method that returns a promise and abstract these complexities. Your controller should look like this:

someService.someMethod().then(function(result) {
  $scope.whatever.push(result);
});

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

How to choose a javascript drop down using selenium?

Here is the HTML code for a JavaScript drop-down menu that contains various options, including "All Resumes". I am attempting to select this option using Selenium WebDriver: <div id="resume_freshness_container"> <div class="dropdown_small_wrapper ...

Creating a nested JSON file dynamically in Angular: A step-by-step guide

I am looking to dynamically generate a nested JSON file within an Angular project. The data will be extracted from another JSON file, with two nested loops used to read the information. Below is an example of the initial JSON file structure: { "data": [ ...

Is it possible to create a looped GLTF animation in three.js using random time intervals?

I am currently exploring the world of game development with Three.js and have a specific query regarding animating a GLTF model. Is it possible to animate the model at random intervals instead of in a continuous loop? In the game I am creating, players wil ...

What is the best way to reach a link using Selenium?

Challenge : Unable to interact with a link using JavaScript through Selenium. Attempted Solutions: element = driver.find_element_by_css_selector(a {href: "javascript:void(0)"}) resulted in a SyntaxError. element = driver.execute_script("ja ...

Attempting to create a single function that can be utilized with numerous divs that share the same class in jQuery

Currently, I am working on creating a basic jquery gallery viewer. In my code, I have the following structure: <div class="photoset"> <img /> <img /> </div> <div class="photoset"> <img /> <img /> <i ...

Interactive window allowing the user to closely examine code

Hey guys, I need your help with something Is there a way (PHP / jQuery) that allows me to zoom in on my code? Similar to how lightbox works for images. I specifically want to zoom in on dynamic code while using Yii's CListView. I'm thinking of ...

Tracking progress in a Rails job using Coffeescript

Recently, I came across a helpful gem called this gem, which allows for the seamless integration of bootstrap progress bars and the delayed job gem. The example provided by the creator uses .haml files, but since my project utilizes erb and coffeescript, I ...

jQuery AJAX issues on Safari and iOS gadgets

I'm facing a compatibility issue specifically with Safari and all iOS devices. I've developed this jQuery code for a project, but it seems to have trouble working with Safari. Interestingly, it works perfectly fine with Chrome, Firefox, and even ...

"A currency must be designated if there is a value present in a monetary field" - The default currency is established

I've encountered a major issue with one of my managed solutions. I have a customized workflow that generates multiple custom entities, each with various money fields. Here's the scenario when I trigger my workflow: The custom workflow enters a ...

Attempting to transmit a dynamic array of promises from Angular to an Express server

Currently, I am attempting to send an array of promises to an express app in order to retrieve data from a mongo database. The behavior seems to be working fine on the front end. In this scenario, both objects are sent to the server and resolved using $q ...

Can config values be dynamically set from an Excel file in Protractor?

I am currently working on parameterizing capabilities using an Excel sheet. For this task, I am utilizing the npm exceljs package for both reading and writing data. Below is a snippet of the code that demonstrates how I am trying to achieve this: //This f ...

AngularJS: utilizing the @ symbol to mention someone in a textarea field

Looking to create an autocomplete form that activates when the "@" symbol is typed in a textarea, similar to the functionality in this library: . I want to achieve this using only AngularJS and CSS. What type of directive would be best for this task? Addi ...

What causes the JavaScript code to output the number 3?

What is the reason behind the output a == 3 in this code snippet? var x = "abc"; var y = 3; var z = "xyz"; var a = x && y || z; Here is the link to interact with the code: http://jsfiddle.net/thinkingmedia/qBZAL/ One might assume that a == true ...

Position the div in the center of a container that is 100% width and has floating elements with dynamic widths

I am looking to align 3 divs inside a container div, with the arrangement of [LEFT] [CENTER] [RIGHT]. The container div should be 100% wide without a fixed width, and I want the center div to stay centered even when resizing the container. The left and ...

A guide to generating an XML file on a user's device through JavaScript or jQuery

Is there a way to generate an XML file on the client's machine using JavaScript or jQuery? I am looking to write an XML file from my web application directly onto the client's machine. What would be the best approach to achieve this across multip ...

Execute controller action upon item selection within KODataTable MVC table

I am displaying data in a table using AJAX to call an Action that returns a JSON list. Output: I want each user (row in the table) to be clickable and linkable to an edit page (Admin/Edit/Id). This can be done either by clicking on them or by having an E ...

Instructions for using arrow keys to navigate between div elementsHow to use arrow keys for navigating through

Is it possible to navigate between div elements using arrow keys like in Notion's editor? <div> hello word </div> <div>hi</div> <div>notion</div> Given the code above, how can one move the cursor to another ...

Transitioning to TypeScript has brought the promise of imports returning once again

I've been facing some challenges while migrating my extensive project to TypeScript, particularly with handling imports. Being relatively new to programming, I'm unsure if my previous approach was considered bad practice. Previously, I organized ...

A step-by-step guide for updating a minor version of Angular with Angular CLI

I've been searching online for the answer to this straightforward question, but can't seem to find it anywhere... In my angular 4 project (made with angular cli), I want to utilize the newly introduced http interceptors in version 4.3. Could so ...

Create a stylish frame around the interior triangle shape

I have created a div containing a triangle shape as shown below: #inner-div { width:200px; height:200px; background-color:black; position:relative; border:2px solid red; } #triangle { border-right:15px solid transparent; border-left:15px s ...