Preserve a retrieved value from a promise in Angular

Upon loading the page, the dropdown menu is populated with various values (such as 1, 2...7). However, when attempting to set a specific value based on a certain condition within a promise, it doesn't seem to work. How can this issue be resolved?

html:

<div ng-app="app" ng-controller="Ctrl">
 <select id="ddlSets" data-ng-model="SetId">
   <option value="0">-- Select Set --</option>
   <option data-ng-repeat="item in Sets" value="{{item.Id}}">{{item.Code}}</option>
 </select>
</div>

ctrl.js:

var app = angular.module("app",[]);
app.controller("ctrl",["$scope","Factory",function($scope,Factory){   


     var init = function(){
      //$scope.Sets = (code here to bind data to the dropdown)

      var promise = Factory.GetSetId();
      promise.then(function (success) {
          if (success.data == 5) {
            $scope.SetId = 5; //The value remains unset despite attempts.
          }
       },
       function (error) {
         console.log(error);
      });
    }
    //It works if set here - $scope.SetId = 7;

            init();
  }]);

factory.js:

app.factory("Factory", ["$http",function ($http) {
var factory = {};
factory.GetSetId = function () {
        return $http({
            url: "http://localhost:12345.asmx/GetSetId",
            method: "GET"
        }).success(function (data, status) {
        }).error(function (data, status) {
        });        
    }
return factory;
}]);

Answer №1

Make the necessary adjustments to your HTML code by implementing scope variables directly in the HTML without using $scope.

<div ng-app="app" ng-controller="Ctrl">
 <select id="ddlSets" data-ng-model="SetId">
   <option value="0">-- Choose Set --</option>
   <option data-ng-repeat="item in Sets" ng-value="{{item.Id}}">{{item.Code}}</option>
 </select>
</div>

Answer №2

Is it possible to set a value to an object property in this way:

controller:

$scope.data = {};
var promise = Service.GetSetValue();
promise.then(function (result) {
  if (result.data == 7) {
    $scope.data.SetValue = 7; //update
  }
},
function (err) {
 console.log(err);
});

template:

<input type="text" data-ng-model="data.SetValue">

Answer №3

It appears that the value of $scope.SetId is 5, which is a number. However, the options element has a value of "5", derived from {{item.Id}}, resulting in a string due to interpolation using {{ }}.

(Note that "5" does not actually contain quotes in the string, they are included here for illustrative purposes regarding data types).

You have two options:

  1. Utilize ngOptions to create the options elements. The following example should suffice:

    <select id="ddlSets" data-ng-model="SetId" ng-options="item.Id as item.Code for item in Sets">
      <option value="0">-- Select Set --</option>
    </select>
    
  2. Strictly use string IDs within the scope. A simple solution would involve converting it to a string before assigning it in the scope.

    if (success.data == 5) {
      $scope.SetId = 5 + '';
    }
    

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

Invoking AJAX function post readystatechange

Currently, I am in the process of making an Ajax call to a server and attempting to invoke another function once the response is ready (readystatechanged). As of now, there isn't any serverside code implemented. Surprisingly, Chrome and Firefox encoun ...

What is the reason behind the undefined value of "this" in this particular class method?

I have scoured the depths of the internet in search of a solution, but I am still grappling with an issue related to a JS class I am developing for a Micro Service (still learning as I go). When attempting to call a method within a class on an instantiate ...

FullPage.js combines traditional scrolling with a unique horizontal slider feature

Visit this link for the example. Hello, I have a question regarding this example: Is there a way to disable the automatic scrolling that occurs when reaching the middle of a page? Also, I am having trouble with the horizontal slider not responding to ...

Testing asynchronous actions in React Redux

Currently encountering an error while testing async actions. The error message reads TypeError: Cannot read poperty 'then' of undefined, pointing to the line below in my code. return store.dispatch(actions.fetchMovies()).then(() => { Below i ...

Using JavaScript to calculate dimensions based on the viewport's width and height

I have been trying to establish a responsive point in my mobile Webview by implementing the following JavaScript code: var w = window.innerWidth-40; var h = window.innerHeight-100; So far, this solution has been working effectively. However, I noticed th ...

json array: Tips for adding elements to a new array

In order to achieve my goal, I am looking to create a JSON array structure similar to the one shown below: var args = [{ name: 'test', value: 1 }, { key: 'test2', value: 2}]; How can I modify the code snippet provided below to generat ...

Two draggable elements and two droppable containers all conveniently placed on a single webpage

My current project involves two sets of draggable elements and two sets of droppable elements. I'm trying to achieve a specific functionality where the first set of draggable elements can only be dropped inside the first set of droppables, while the ...

Strange spacing in Angular Material checkbox

I have a container with an angular material checkbox inside. The background of the container is black, so I changed the background color of the checkbox to white for visibility. However, there seems to be some unwanted spacing on the right side of the chec ...

HTML link with "mailto:" not opening in a new tab

Just posted for the first time! I'm attempting to create a mailto link using 'templated' JavaScript that pulls specific data from a JSON object: var menu = { "menu": [ { "title": "let's talk", "link": "mailto:<a href ...

What could be the reason why the @media print selector is not showing the correct format when I try to print?

When I click the print button, the text is supposed to display in four columns in the print dialog, but it appears as paragraphs instead. This is my script code where there is a click event for the print button. When I click on it, the print dialog pop ...

Is using "move(-1)" considered incorrect in an AngularJS expression?

Encountering this error message: [$parse:ueoe] Unexpected end of expression: move( When using this snippet of code: <button type="button" ng-click="move(-1)" tabindex="-1"> Could there be a syntax issue with move(-1) in AngularJS? On a side note, ...

What is the best way to keep tab content fixed when switching?

I've successfully implemented tab switching, but I need to make the content fixed. How can I achieve this so that no matter the length of the content, it remains fixed in its position when switching tabs? The current issue is that when the content is ...

Content Security Policy directive violation: Chrome extension policy error occured due to refusal to execute inline event handler

I've been working on a chrome extension to perform a simple task, but I've hit a roadblock with one line of HTML code that's causing issues with setting the correct permissions. Despite my efforts, I'm stuck on what exactly needs to be ...

What is the best way to display the time of a post update similar to the style of

I am currently working on creating a notification deck. Instead of displaying the time when a notification was received, I aim to show the time that has passed since its arrival similar to how Twitter and Facebook do it with formats like "32m" or "1 hour a ...

Encountered an error when attempting to access the property "addOption" on an undefined object

Every time I try to implement search functionality, I keep running into this error: "cannot read property 'addOption' of undefined in JavaScript selectize." I have confirmed that my result array does contain data. This is my JavaScript code: ...

Modify the colors of names within an array of point names and their corresponding y values using Highcharts

I am trying to customize the color for each point in an array based on its name and y value. This is what I have so far: (function(H) { H.wrap(H.Series.prototype, 'getColor', function(proceed) { this.color = generateColorForString(this.na ...

Identifying line breaks caused by browsers or CSS forced line breaks

<p style="width:60px"> This is just a sample text. It is a piece of text that doesn't really say anything meaningful.</p> When this text is rendered as HTML, it would look like this: This is just a sample text. It is a piece of text ...

Calculating the total of an array's values using JavaScript

Receiving information from an API and looking to aggregate the values it contains. Consider the following code snippet: function totalPesos(){ $http.get('/api/valueForTest') .then(function(data){ $scope.resumePesos = data.data.Re ...

Ways to add a substantial quantity of HTML to the DOM without relying on AJAX or excessive strings

Currently, I am looking to update a div with a large amount of HTML content when a button on my webpage is clicked. The approach I am currently using involves the .html() method in JQuery, passing in this extensive string: '<div class="container-f ...

Combining two observable entities

Utilizing Angular 4 and rxjs, the objective is to fetch data from two distinct servers in JSON format, merge this data, and exhibit it in a list by associating the list with an observable array. **Word Search Component TypeScript File:** @Component( ...