Search code examples
javascriptjsonangularjsangular-ngmodel

AngularJs ng-model bind from json


I have following dropdown:

          <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 angular I get a data in json format:

   $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);
  }

In view I can't assign the json data to ng-model="produk.category" but it works for <p>Selected: {{produk.category}}</p>

This is what returned by json Object {category: 'Tours'}

Thanks!!


Solution

  • The problem you are facing is that you are trying to read a property in your model that doesn't exist. Particularly in this line:

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

    From the code you have the value that is selected is produk.category. Inside there there is only the string "Tours". And an string in Javascript has no property called name.

    AngularJS normal behavior is to ignore when properties don't exist. So you get nothing. Changing it to this:

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

    will solve your problems (since now you are printing the string, not a non-existing property called "name" in your string).