我无法使用AngularJS创建SELECT标记

时间:2014-01-14 16:28:31

标签: angularjs

我无法使用AngularJS构建SELECT TAG HTML。有人能帮助我吗?问题在于我猜ng-repeat

我有一个 Json 响应:

[{
        "Unity": [
            {
                "Name": "ASD ALSKJD ASLKJ ASLD",
                "Code": "11106600"
            },
            {
                "Name": "AioPE PW pIOW DPOIUWD POFIWU PFOIW",
                "Code": "11106601"
            },
            {
                "Name": "APOIU Ppeoiupo8uepo8uwp IUPD FOIUS PFOISDU",
                "Code": "11106602"
            }
        ]
}]

我的控制器是:

function MyController($scope, $http) {
        $scope.url = 'pathtocontroller/controller.asp'; //the response of json is from here
        $http.get($scope.url).success(function (data, status) {
            $scope.Name = data.Name;
            $scope.Code = data.Code;
        }).error(function (data, status) {
                $scope.response = 'Request failed';
            });
}

我的 HTML 是:

<div class="grid-6-12" ng-controller='MyController'>
    <label>A label for unity <em class="formee-req">*</em></label>
    <select class="formee-small" ng-repeat="Name in Name">
        <option value=" {{Code}} ">{{Name}}</option>
    </select>
</div>

2 个答案:

答案 0 :(得分:2)

Angular中实际上有一个特定的指令用于实现选择 - see the documentation here

作为文档的一个例子:

<select ng-model="color" ng-options="c.name for c in colors">
      <option value="">-- choose color --</option>
</select>

重要提示: 如果您使用此指令,然后查看生成的HTML代码,您会注意到每个生成的<option>的值是整数0,1,2,...这可能会让您失望,但您只需要知道Angular在内部使用这个值,如果你引用模型(上例中的$scope.color),它将包含正确的值。

因此,在您的情况下,您可以执行以下操作(更新以匹配您的控制器设置):

function MyController($scope, $http) {
    $scope.url = 'pathtocontroller/controller.asp'; //the response of json is from here
    $http.get($scope.url).success(function (data, status) {
            $scope.data = data[0].Unity;
        }).error(function (data, status) {
            $scope.response = 'Request failed';
        });
}

然后在你的模板中:

<div class="grid-6-12" ng-controller="MyController">
    <label>A label for unity <em class="formee-req">*</em></label>
    <select ng-model="option" ng-options="row.Name as row.Code for row in data">
    Selected: {{ option }} <!-- just to show it is working -->
</select>
</div>

实施例

以上是上述工作示例:http://jsfiddle.net/eGCKa/2/

答案 1 :(得分:1)

您的控制器有点偏离:

function MyController($scope, $http) {
    $scope.url = 'pathtocontroller/controller.asp'; //the response of json is from here
    $http.get($scope.url).success(function (data, status) {
        $scope.returnedData = data[0].Unity[0]; // or however you access the Unity object
    }).error(function (data, status) {
            $scope.response = 'Request failed';
        });
}

然后调整你的html:

<select class="formee-small" ng-repeat="item in returnedData">
    <option value=" {{item.Code}} ">{{item.Name}}</option>
</select>