Leveraging AngularJs by binding ng-model to data from a JSON

Below is the code for a dropdown selection:

<h3>Selectize theme</h3>
  <p>Selected: {{produk.category}}</p>
  <ui-select ng-model="produk.category" theme="selectize" ng-disabled="disabled" style="width: 300px;">
    <ui-select-match >{{$select.selected.name}}</ui-select-match>
    <ui-select-choices repeat="cat in categories | filter: $select.search">
      <span ng-bind-html="cat.name | highlight: $select.search"></span>

    </ui-select-choices>
  </ui-select>

In my Angular application, I retrieve data in JSON format like this:

$scope.getProductToEdit = function(id){
      Account.getProductToEdit(id)
        .then(function(response){

            $scope.produk = response.data.product;

            //console.log($scope.produk); ---> return json
            return $scope.produk;
        })
        .catch(function(response){

        })
    }

if($stateParams.id){
    $scope.getProductToEdit($stateParams.id);
  }

I am facing an issue where I cannot assign the JSON data to ng-model="produk.category", even though it works for

<p>Selected: {{produk.category}}</p>

The JSON object returns as follows: Object {category: 'Tours'}

Thank you!

Answer №1

It seems like the issue you're encountering stems from attempting to access a property in your model that doesn't actually exist. Specifically, take a look at this line of code:

<ui-select-match >{{$select.selected.name}}</ui-select-match>

Based on the provided code snippet, it appears that the selected value is produk.category, which contains only the string "Tours". In JavaScript, a string does not have a property called name.

In typical AngularJS behavior, non-existent properties are simply ignored, resulting in nothing being displayed. To resolve this issue, you can modify the code as follows:

<ui-select-match >{{$select.selected}}</ui-select-match>

By making this adjustment, you will be outputting the string itself rather than trying to access a nonexistent property named "name" within your string.

Answer №2

Give this a shot

  $scope.fetchProductToModify = function(identifier){
  Account.getProductToEdit(identifier)
    .then(function(response){
        $scope.item = {}
        $scope.item.category = response.data.product.category;

        //console.log($scope.item); ---> return as json
        return $scope.item;
    })
    .catch(function(error){

    })
}

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

I'm looking for ways to incorporate TypeScript definition files (.d.ts) into my AngularJS application without using the reference path. Can anyone provide

I'm interested in leveraging .d.ts files for enhanced intellisense while coding in JavaScript with VScode. Take, for instance, a scenario where I have an Angular JS file called comments.js. Within comments.js, I aim to access the type definitions prov ...

Generate a fresh array by appending a JSON element and inserting a new attribute into the same JSON object that was appended

I have a JSON array and I am looking to create a new array where I can push all childNodes along with their respective funding source names. var data = vardata={ "costdata": [ { fundingSource: 'A', childNode: [ ...

there is no data in the response

Upon fetching the response data, I am currently receiving nil. func fetchSinglePageData() { var response: NSData? var errors: NSError? dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), { response = NSData(c ...

Angular restricts the use of the svg namespace in the $sce service for security reasons

I have a project in Angular Material where I am using an md-icon with a specific svg structure: <md-icon class="ic1" md-svg-src='data:image/svg+xml, <svg xmlns="https://www.w3.org/2000/svg" viewBox="0 0 32 32"> <ellipse ry="16" rx=" ...

Exploring Vue and Webpack: Optimizing global variables for development and production environments

I have been using vue-cli to create my web application. Throughout the app, I am making use of an API by including it in various places like this: axios.post(API + '/sign-up', data).then(res => { // do something }); The API variable is a c ...

Tips for adding content to a textarea with JavaScript without disrupting the editing history

I have a specific requirement where I want the user to be able to highlight text in a textarea, then press ctrl + b to automatically surround that selected text with stars. Here is what I envision happening: 1) The initial content of the textarea is: "he ...

The removeAttribute function has the ability to remove the "disabled" attribute, but it does not have the capability to remove

When it comes to my JavaScript code, I have encountered an issue with two specific lines: document.getElementsByName('group')[0].removeAttribute('disabled'); document.getElementsByName('group')[0].removeAttribute('checke ...

Creating a JavaScript function to download specific sections of an HTML page

Currently, I am implementing PHP MySQL in my HTML page. I have already utilized several div elements in my page. I successfully created a print button that prints a specific div on the page. Now, I am looking to add a download button that will allow users ...

Implementing a document update event using jQuery

On my WordPress site, I am using a responsive lightbox plugin. When an image is clicked, it opens a popup box with the ID fullResImage. Now, I would like to incorporate the Pinch Zoomer function to it. Do I need to bind a function for this, or is there a s ...

The Google Picker API encounters a server error when attempting to retrieve the OAuth token after being released as a private add-on

Recently, I encountered a puzzling issue with my script that utilizes the Google Picker API. During testing, everything worked flawlessly until I decided to publish it as a private add-on. From that point on, the script's getOAuthToken function starte ...

Implementation of Datatable Server-Side Using Json/Ajax Demonstrated Successfully, with CRUD functionality pending

Introduction: My current project involves using a server-side datatable.net JQuery plug-in with JSON, AJAX, and ssp.class.php. Although I have managed to get it working, I am facing challenges while trying to create buttons for editing and deleting entries ...

Issues have been encountered with Angular 5 when trying to make required form fields work properly

Just created my first Angular app using Angular 5! Currently following the documentation at: https://angular.io/guide/form-validation. Below is the form I have set up: <form class="form-container"> <mat-form-field> <input matInput pl ...

Angular form submission with action appending key-value pairs

My main objective was to create a form submission using the 'get' method, where key-value pairs are appended to the URI. I referred to http://www.w3schools.com/tags/att_form_method.asp, which explained how setting the form method as "get" should ...

Having trouble importing a variable from a precompiled library in TypeScript JavaScript

Here is the content of my package.json file: { "name": "deep-playground-prototype", "version": "2016.3.10", "description": "", "private": true, "scripts": { "clean": "rimraf dist", "start": "npm run serve-watch", "prep": "browserify ...

Challenges with jQuery: Appending strings to a dynamically selected element

Hello everyone, I have a question regarding adding the string 'url(" ")' around my Any assistance you can provide would be greatly appreciated. Thank you! $(function() { $('#list li a').hover( function(){ $("#meow").css( " ...

Failed attempt to convert JSON-formatted NSString into an NSArray

Forgive me for adding another question about converting to NSArray, but despite reading numerous posts on the same topic, I still can't seem to make it work. It appears to be a simple task, but... - (void) parseList : (NSString *) str { NSLog(@" ...

Deleting square brackets from a JSON file in Node.js is a task that can easily be

I am looking to either remove the square brackets "[ ]" from a JSON object or concatenate multiple arrays of objects into one. This code snippet is used to count the current stock. currentStock : ( req, res, next) => { var listed_item = _(arr_ite ...

Execute AngularJS directive once TypeKit finishes loading the font

I recently created a custom directive to retrieve the position of text on a page, but unfortunately, the position returned is incorrect due to the directive running before TypeKit has fully loaded the font. app.directive('myDirective', function( ...

The Apollo client's GraphQL query encountered an unforeseen termination of the JSON input stream

I have customized my NextJS site with WP WooCommerce integration. By default, the query result only returns up to 100 items, but I have increased it to 1000 without any issue. When I send a request with a query like this: query MyQuery { products(fir ...

Transforming SOAP Response XML into JSON using XSJS

Need assistance with converting an XML response file to JSON using XSJS. Any advice would be highly appreciated. Thank you! ...