Assigning isolate scope property to ngSelect element's directive for the purpose of pre-selecting an option has proven to result in

Upon loading my page, the form is populated with values fetched from an http service. At the top of the form sits a custom directive, specifically a select box:

.directive('categorySelectBox', function(){

  return {
    restrict: "A",
    replace: true,
    scope: {
      // all properties here need to be added to 
      // the directive in order to be picked up
      taxonomies: '='
      ,chosen: '='
    },
    templateUrl: "ngapp/js/tpl/select-box.html"
  };

})

The template for this directive is as follows:

<select class="form-control" 
  ng-options="option.label for option in taxonomies track by option.value" 
  ng-model="chosen" 
  chosen="chosen" 
  taxonomies="taxonomies">
<option value="">Please select a category</option>

My controller implementation looks like this:

.controller('DashboardCtrl', ['$scope', 'DbResourceSrv', function($scope, DbResourceSrv){

  $scope.$watch('cid', function() {
    $scope.formBusy = true;
    $scope.c = DbResourceSrv.getDbResource('response.php', 'company', $scope.cid)
            .then(function(data) {
                $scope.c = data;
                angular.forEach(data, function(value, key) {
                    $scope.c.push({key: value});
                });
            });

    $scope.tax = DbResourceSrv.getDbResource('response.php', 'taxonomy', '')
            .then(function(data) {
                $scope.taxonomies = [];
                $scope.chosen = [];
                angular.forEach(data, function(value, key) {
                    $scope.taxonomies.push({label: value.name, value: value.term_taxonomy_id});
                });
                var catId = $scope.c.category - 1;
                $scope.chosen = $scope.taxonomies[catId];
                $scope.formBusy = false;
            });
  });


  $scope.updateCompany = function(cid) {
    var formData = $scope.c;
    $scope.formBusy = true;
    $scope.doCompanyUpdate = DbResourceSrv.updateDbResource('response.php', cid, formData)
            .then(function(response) {
                $scope.formBusy = false;
            });
  };
}]);

Typically, I expect to see the category loaded from the database separately via $scope.tax.

However, my attempts at using $watch on the chosen scope property have not yielded the desired results. Similarly, employing a directive controller to ensure that scope.chosen is set there hasn't resolved the issue. It seems that when both processes are initiated with promises, the category fetching fails if one loads before the other due to their tight coupling.

Do you have any suggestions for code enhancements to prevent the default Please select a category option from being automatically selected upon page load?

Answer №1

Your analysis is spot on: there are two promises that may not resolve in the intended order, causing an issue. When the second promise completes before the first, it cannot calculate catId as $scope.c is still empty.

$scope.c = DbResourceSrv.getDbResource('response.php', 'company', $scope.cid)
.then(function(data) {
    $scope.c = data; // might not be ready when needed
});

$scope.tax = DbResourceSrv.getDbResource('response.php', 'taxonomy', '')
.then(function(data) {
    var catId = $scope.c.category - 1;
    $scope.chosen = $scope.taxonomies[catId];
});

The solution lies in utilizing $q.all, which can handle multiple promises and only resolves when all of them are fulfilled.

Implementation would resemble this:

$q.all([$scope.c, $scope.tax]).then(function(results){
    var catId = $scope.c.category - 1;
    $scope.chosen = $scope.taxonomies[catId];
});

Check out a demo here

You can retain most of your existing promise callbacks, just ensure to move any logic dependent on both AJAX requests being completed.

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

Show a div element when clicking on a different div element

Three images have been added. Please take a look: https://i.sstatic.net/R4IgG.png What would be the optimal approach to create a similar layout? My current idea involves creating a large container after each row, which is initially collapsed. Upon clickin ...

What are the best practices for handling dynamic content internationalization in Angular?

According to Angular.io, the i18n tag is used to mark translatable content. It should be placed on every element tag that requires translation of fixed text. Now, what if we have an element with dynamic content? For example, consider a table displaying a ...

React Native Issue: The mysterious disappearance of the 'navigation.push' object

I am trying to navigate to List.js after clicking a button in the MainMenu.js file, but I keep encountering this error: TypeError: undefined is not an object (evaluating 'navigation.push') This snippet is from my App.js file import { StatusBar ...

Implementing TestCafe with a Rails backend and utilizing fixtures data for testing

Currently, I am involved in a Rails project that utilizes RSpec for testing. We rely on various Rails fixture data to test our UI under different conditions. Recently, I came across TestCafe for handling functional UI testing, and I find it quite intrigui ...

Combining arrays within an array using the concat method in JavaScript instead of the push method

I am facing a challenge that requires me to merge arrays of an array and produce a single array with the format [ array[0][0], array[0][1], array[1][0], array[1][1], etc. ]. To solve this, I utilized the `push` method within nested for-loops. However, the ...

Prevent typing on input fields for numbers exceeding 3 digits

How can I prevent users from entering a number with more than 3 digits? For example, allowing entries like 150 but not accepting numbers like 1601. The keypress should be disabled in such cases. The keypress event must be disabled. <template> < ...

Is there a way for me to access the information within these curly brackets [[]}?

I'm facing a challenge where I need to extract the ID from an API response that is formatted in a way unfamiliar to me. As a result, I'm unsure of how to retrieve the ID data from this response. (This is my initial query, so if it's unclear ...

Having trouble manipulating state in JavaScript for React Native?

Encountering an issue when attempting to use the setState function in React Native. Code Snippet import React from "react"; import { TextInput, Text, View, Button, Alert } from "react-native"; const UselessTextInput = () => { st ...

Instead of logging an "Error" message along with a stack trace, log a "Warning"

If I were to utilize new Error() or new TypeError(), the resultant stack trace would resemble the following: Error: Live-Mutex client lock request timed out after 6000ms I am curious if there exists a method to create a message that commences with "Warni ...

The execution of the HTTP request is not happening

As a newcomer to JS and Node, I am attempting to display a JADE view using JSON obtained from a REST API. Everything works perfectly when I run the http.request on its own, but as soon as I introduce modules and rendering statements, the http request funct ...

I'm having trouble getting a http.request to run within an imported module. It just doesn't seem to work when I try to access

Here is the code from my main.js file: var spaceJson = require('./space.js'); var options = { "method": "GET", "hostname": "10.10.111.226", "port": null, "path": "/API/Org", "headers": { "authorization": "Bearer eyJ0eXAiOiJKV1QiLCJ ...

Exploring the wonders of AngularJS UI Router through HTTP GET requests

Looking for guidance on how to execute an http Get request in Angular using UI router when a template is loaded for my first Angular app. Any help would be appreciated. Thanks! Here is a link to the Plunker I have set up: http://embed.plnkr.co/LRSGXqxjtbY ...

Issue with making requests across origins in Vuejs using axios

Currently, I am utilizing Vuejs and axios for handling web requests. So far, I have successfully managed to perform GET, POST, and PUT operations. However, the new challenge that I am facing is uploading media to the server. The server necessitates sending ...

Is it possible to link the value of an input[range] to an array?

I want to create an array called arr dynamically with a length based on the value of ng-model (numberFloor) from an input[type=range]. var app = angular.module("houseBuilder", ['ngSanitize']); app.controller('myCtrl', function($scop ...

Exploring the process of sending various variables from PHP to a jQuery function

I have a jQuery function that prints charts using the jqPlot framework. I need to print multiple charts with different options, so I have to call this function several times with varying values. My current approach is not very elegant: //----- index.php: ...

Inquiring about socket.io: How can an io emit its own signal?

I am currently working on implementing the emit event in an express router, and I'm attempting to pass a global.io variable. However, I've encountered an issue where despite adding the following code: io.emit('join','Tudis' ...

adjusting the color of ion-button when hovering over the cancel button

I'm working on a button bar for my app and I want the color of the button to change based on its state (false, true). Currently, the button starts out green, turns light green when hovered over, and becomes white when clicked. Once I click it, the bu ...

Obtain the names of the cities that the Google Maps route passes through

Currently working on a website that integrates Google Map API v3. Is there a method to gather the names of the places or cities along the route from point A to B? The page utilizes JavaScript for functionality. ...

Is it possible to run a JavaScript script from any location?

Currently, I am diving into a Javascript script and in order to run it seamlessly from any webpage I am browsing, I am thinking of adding a button to my bookmarks or using an extension. To be honest, I am clueless about the process and despite doing some ...

Updating several inputs programmatically in VueJSLet's explore how to

I am working on a form that requires updating multiple other fields when one field is updated. For instance, I have a contact name field and depending on the name entered, I need to update the email and phone number fields as well. <template> < ...