2015-04-13 4 views
0

В настоящее время я работаю над этим кодом: Как заполнить несколько элементов с помощью общей функции (AngularJS)?

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

ответ

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')" 

 Смежные вопросы

  • Нет связанных вопросов^_^