AngularJS를 사용하여 모범 사례를 찾고 있습니다. 거래 내용은 다음과 같습니다.AngularJS - 컨트롤러간에 기능을 공유하는 방법
양식이있는 두 개의 서로 다른 페이지가 있으며 각 페이지에는 양식 필드가 있습니다. 그러나 두 양식 모두에 공통된 기능이 하나 있습니다. 사용자가 시스템에있는 여러 전자 메일 주소를 선택할 때 사용할 수있는 자동 완성 필드가 있습니다.
선택한 이메일 주소는 HTML 페이지에 표시 될 수 있도록 모델/범위에 저장됩니다.
<div ng-controller="MyCtrl">
<form ng-submit="selectCurrentEmail()" novalidate>
<input type="text"
class="form-control"
ng-model="responsiblePerson" />
<input type="submit" value="Add" />
<div ng-repeat="email in formData.selectedEmails">
<div>
{{email}} <a href="" ng-click="removeEmail(email)">x</a>
</div>
</div>
</form>
</div>
와 AngularJS와 부분 : 예를 들면 다음과 같습니다이다
var myApp = angular.module('myApp', []);
function MyCtrl($scope) {
$scope.formData = {selectedEmails: []};
$scope.selectEmail = function(email) {
if (email != null && $.inArray(email, $scope.formData.selectedEmails) == -1) {
$scope.formData.selectedEmails.push(email);
$scope.responsiblePerson = null;
}
};
$scope.removeEmail = function(email) {
var index = $.inArray(email, $scope.formData.selectedEmails);
if (index != -1) {
$scope.formData.selectedEmails.splice(index, 1);
}
};
$scope.selectCurrentEmail = function() {
$scope.selectEmail($scope.responsiblePerson);
};
}
이 (가 주요 문제는 여기에 없습니다 이후 자동 완성 포함되어 있지 않습니다 ..)
이를 모두 정상적으로 작동하지만 두 컨트롤러에서 동일한 로직을 반복하고 싶지 않습니다. 내가 원하는 것은 선택한 이메일 주소를 설정하고 제거 할 수있는 서비스 또는 기본 컨트롤러입니다. 사용자가 완료되면 범위에 선택한 이메일 주소 만 포함됩니다.
그래서 세 가지 기능을 범위에서 일반화하는 좋은 방법이 있다고 생각합니까? 이보다 더 좋은 아이디어가 있습니까?
제안했듯이 자동 완성 필드에 대한 지시 모듈을 작성하면 – Sprottenwels
각도 서비스를 저장할 수 있습니다. [한 컨트롤러가 다른 각도로 AngularJS를 호출 할 수 있습니까?] (http://stackoverflow.com/questions/9293423/can -one-controller-call-another-in-anglesjs) – Stewie
서비스를 사용하는 것이 더 나은 옵션입니다. – BKM