0

我目前正在处理这段代码:

<select class="form-control"
        ng-init="agreementTypes = initAgreementTypes('ManageMission/GetDescriptions/?type=AgreementTypes')"
        ng-model="mission.AgreementType"
        ng-options="at.Content for at in agreementTypes"></select>
 <select class="form-control"
         ng-init="agreementStatus = initAgreementStatus('ManageMission/GetDescriptions/?type=AgreementStatus')"
         ng-model="mission.AgreementStatus"
         ng-options="as.Content for as in agreementStatus"></select>
$scope.initAgreementStatus = function (url) {
    $http.get(url).
        success(function (data, status, headers, config) {
            $scope.agreementStatus = data;
        }).
        error(function (data, status, headers, config) {
            console.log("data: " + data);
            console.log("status: " + status);
            console.log("headers: " + headers);
            console.log("config: " + config);
        });
};

$scope.initAgreementTypes = function (url) {
    $http.get(url).
        success(function (data, status, headers, config) {
            $scope.agreementTypes = data;
        }).
        error(function (data, status, headers, config) {
            console.log("data: " + data);
            console.log("status: " + status);
            console.log("headers: " + headers);
            console.log("config: " + config);
        });
};

这段代码有效,但它很丑陋。我想合并这两个函数,但我不知道最好的方法。我已经阅读了一些关于承诺的文章。请记住,我希望将 URL 保留在 HTML 部分中。

4

1 回答 1

0

您可以使用方括号 访问$scope任何其他属性:Object$scope['agreementTypes']

这样,您可以添加属性的名称,响应应分配给:

$scope.initDescriptions = function (target, url) {
  $http.get(url)
    .success(function (data, status, headers, config) {
      $scope[target] = data;
    })
    .error(function (data, status, headers, config) {
      console.log("data: " + data);
      console.log("status: " + status);
      console.log("headers: " + headers);
      console.log("config: " + config);
    });
};

在您的标记中,应用以下更改:

ng-init="initDescriptions('agreementTypes', 'ManageMission/GetDescriptions/?type=AgreementTypes')"
于 2015-04-13T15:42:44.597 回答