2017-06-02 53 views
-1

当用户选择该选项时,我通过在页面上打印出的选择框选择了我的对象。只能获得第一级对象

但是,它当前会打印嵌套在父对象中的父对象和所有其他对象。

我的数组

$scope.productsandformats = [ 
    { 
       "Pname": "parent", 
       "format": [ 
        {"Fname": "child", "id": "4"}, 
        {"Fname": "second child", "id": "5"} 
       ] 
      } 
]; 

我的角度和HTML选择框

<select ng-model="formData.ProductType" 
     ng-options="product.Pname for product in productsandformats"> 
    <option value="">- Please Choose -</option> 
</select> 

<pre class="col-sm-12 ng-binding"> 
    {{ formData }} 
</pre> 

所以目前的例子,当我选择parent我得到

{“ProductType “:{” PNAME “:” 括号t“,”format“:[{”Fname“:”child“,”id“:”4“},{”Fname“:”second child“,”id“:”5“}]}}

我希望看到什么

{ “ProductType”:{ “PNAME”: “父”}}

我需要什么

我只是想请参阅Pname这样的顶级lev el对象,如parent, parent2, parent3等不是子对象。

我该如何改变这个只显示顶级对象?

@George回答几乎工程

困难我第二个下拉应与选定的父母和最后一个字符串的子对象来填充内容应为以下,如果从第二个第一选项,然后第二个孩子选择父选项。

产品型号:PNAME:父,formatType:FNAME:两个箱子孩子

**角码,第二填充了选定的父母子女**

<select ng-model="formData.ProductType" 
      ng-options="product.Pname for product in productsandformats"> 
     <option value="">- Please Choose -</option> 
    </select> 

    <select ng-model="formData.formatType" 
      ng-options="format.Fname for format in formData.ProductType.format" 
      ng-if="formData.ProductType"> 
     <option value="">- Please Choose -</option> 
    </select> 
+0

这是JSON不是杰森。 –

+0

...这与JSON(或Jason)没有任何关系。 – JJJ

+0

是我的拼写错误,谢谢你的看法,我怎么会认为投票简单的拼写错误有点多 – Beep

回答

2

如果您阅读ngOptions可以使用select as指定为对象被设定在ngModel

对于第二个选择我建议有第一选择的ng-change该对象存储上,您可以使用第二选择范围的另一个变量。

var myApp = angular.module('myApp', []); 
 

 
function MyCtrl($scope) { 
 
    $scope.productsandformats = [{ 
 
    "Pname": "parent", 
 
    "format": [{ 
 
     "Fname": "child", 
 
     "id": "4" 
 
    }, { 
 
     "Fname": "second child", 
 
     "id": "5" 
 
    }] 
 
    }]; 
 

 
    $scope.formats = []; 
 

 
    $scope.productTypeChange = function() { 
 
    $scope.formats = $scope.productsandformats.find(ps => ps.Pname == $scope.formData.ProductType.Pname); 
 
    } 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> 
 
<div ng-app="myApp"> 
 
    <div ng-controller="MyCtrl"> 
 
    <select ng-model="formData.ProductType.Pname" ng-change="productTypeChange()" ng-options="product.Pname as product.Pname for product in productsandformats"> 
 
    <option value="">- Please Choose -</option> 
 
    </select> 
 
    <select ng-model="formData.formatType" ng-options="format.Fname for format in formats.format" ng-if="formData.ProductType.Pname"> 
 
    <option value="">- Please Choose -</option> 
 
    </select> 
 
    <pre class="col-sm-12 ng-binding"> 
 
    {{ formData }} 
 
    </pre> 
 
    </div> 
 

 
</div>

+0

看起来不错,将需要花费一些小分队为我的代码改变它,因为我有两个选择框,第二个填充取决于第一选择。链接和信息+1。 – Beep

+0

@Beep好的,我已经编辑了包含代码,如果你想它被输出为“{”ProductType“:”parent“} – George

+0

我更新了我的问题将完整的代码 – Beep

0

你可以访问像这样的第一级对象

<div ng-repeat='p in formData.productType'> 
{{p.pname}} 
</div> 
相关问题