2013-10-28 6 views
0

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); 
    }; 
} 

http://jsfiddle.net/PqpYj/

이 (가 주요 문제는 여기에 없습니다 이후 자동 완성 포함되어 있지 않습니다 ..)

이를 모두 정상적으로 작동하지만 두 컨트롤러에서 동일한 로직을 반복하고 싶지 않습니다. 내가 원하는 것은 선택한 이메일 주소를 설정하고 제거 할 수있는 서비스 또는 기본 컨트롤러입니다. 사용자가 완료되면 범위에 선택한 이메일 주소 만 포함됩니다.

그래서 세 가지 기능을 범위에서 일반화하는 좋은 방법이 있다고 생각합니까? 이보다 더 좋은 아이디어가 있습니까?

+1

제안했듯이 자동 완성 필드에 대한 지시 모듈을 작성하면 – Sprottenwels

+0

각도 서비스를 저장할 수 있습니다. [한 컨트롤러가 다른 각도로 AngularJS를 호출 할 수 있습니까?] (http://stackoverflow.com/questions/9293423/can -one-controller-call-another-in-anglesjs) – Stewie

+0

서비스를 사용하는 것이 더 나은 옵션입니다. – BKM

답변

1

이것은 UI 요소이므로 논리를 지침으로 사용합니다.

myApp.directive('mailSelector', function() { 
    return { 
     scope: { 
      emails: '=' 
     }, 
     template: '<form ng-submit="selectCurrentEmail()" novalidate>' + 
     '<input type="text"'+ 
     '  class="form-control"'+ 
     '  ng-model="responsiblePerson" />'+ 
     '<input type="submit" value="Add" ng-click="selectCurrentEmail()" />'+ 

     '<div ng-repeat="email in emails">'+ 
     ' <div>' + 
     '  {{email}} <a href="" ng-click="removeEmail(email)">x</a>' + 
     ' </div>' + 
     '</div>' + 
    '</form>',   
     link: function($scope, $element, $attrs) { 
      $scope.selectCurrentEmail = function() { 
       $scope.selectEmail($scope.responsiblePerson); 
      } 

      $scope.selectEmail = function(email) { 
       if (email != null && $.inArray(email, $scope.emails) == -1) { 
        $scope.emails.push(email); 
        $scope.responsiblePerson = null; 
       } 
      } 

      $scope.removeEmail = function(email) { 
       var index = $.inArray(email, $scope.emails); 
       if (index != -1) { 
        $scope.emails.splice(index, 1); 
       } 
      }; 
     } 
    }; 
}); 

컨트롤러는 지시어로 정의 emails 매개 변수를 통해 지침에서 이메일 목록을 검색 할 수 있습니다.

나는 JSFiddle here을 만들었습니다.

자동 완성을 위해 이전에 입력 한 이메일 주소를 공유하려면 이전에 입력 한 이메일 주소 목록이있는 서비스를 사용하도록 지시문을 수정하십시오.

+0

고마워요, 이건 ** 정확히 ** 찾고있는 것입니다! 여전히 AngularJS의 모든 좋은 것들을 배우고 있습니다. 나는 당신이 그런 링크 기능에서 바로 범위에 접근 할 수 있다는 것을 깨닫지 못했다. :) – Janne

관련 문제