AngularJs ng-model绑定来自json

时间:2015-10-07 04:22:16

标签: javascript json angularjs angular-ngmodel

我有以下下拉列表:

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

在角度我得到一个json格式的数据:

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

在视图中,我无法将json数据分配给ng-model="produk.category",但它适用于<p>Selected: {{produk.category}}</p>

这是json Object {category: 'Tours'}

返回的内容

谢谢!

2 个答案:

答案 0 :(得分:2)

您面临的问题是您正在尝试读取模型中不存在的属性。特别是在这一行:

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

从代码中,您选择的值为produk.category。里面只有字符串"Tours"。 Javascript中的字符串没有名为name的属性。

AngularJS正常行为是在属性不存在时忽略。所以什么都没得到。将其更改为:

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

将解决您的问题(因为现在您正在打印字符串,而不是字符串中名为"name"的不存在的属性)。

答案 1 :(得分:0)

试试这个

  $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){

    })
}