AngularJs ng-model bind from json

試著忘記壹切 提交于 2019-12-12 00:25:43

问题


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!!


回答1:


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).




回答2:


Try this

  $scope.getProductToEdit = function(id){
  Account.getProductToEdit(id)
    .then(function(response){
        $scope.produk = {}
        $scope.produk.category = response.data.product.category;

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

    })
}


来源:https://stackoverflow.com/questions/32983771/angularjs-ng-model-bind-from-json

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!