2013-12-10 3 views
0

두 개의 필드가있는 사용자 정의 이메일 텍스트 상자 구성 요소를 만들려고합니다. (I 값의 다른 종류를 통과 할 수 있도록하려면이 지침에서AngularJS : 지시문 바인딩

<div ng-custom-txt></div> 

:

<div class="custom"> 
    <div class="username" contenteditable="true"></div> 
    <div class="domain">@{{ domainValue }}</div> 
</div> 

그래서 내가 좋아하는 그 템플릿을 호출하는 지시어를 호출 할 수 있습니다 :이 작업을 수행하기 위해 나는이 템플릿을 모델에서 도메인)처럼, "NG-DOMAINDATA"라고 :

<div ng-domaindata="mydomain1.com" ng-custom-txt></div> 

내 질문입니다, 내가 템플릿에있는 "도메인"필드로 지시를 결합 할 수있는 방법?

나는이 방법을 사용하려고하지만, 전혀 성공 :

템플릿 : customtemplate.html

<div class="custom"> 
    <div class="username" contenteditable="true"></div> 
    <div class="domain">@{{ domainValue }}</div> 
</div> 

페이지

<div ng-domaindata="mydomain1.com" ng-custom-txt></div> 
<div ng-domaindata="mydomain2.com" ng-custom-txt></div> 

지침

app.directive('ngCustomTxt', function() { 
    return { 
    restrict: 'A', 
    require: '^ngModel', 
    templateUrl: 'customtemplate.html', 
    link: function(scope, element, attrs, ctrl) { 
     scope.$watch(attrs.ngDomaindata, function (newValue){ 
     scope.domainValue = newValue; 
    } 
    } 
    } 
}); 

이 두 요소를 구분할 수 없기 때문에 분명히 작동하지 않습니다. 누군가 나를 도와 줄 수 있습니까?

+0

. 접두사 ng를 사용하여 직접 지시문을 사용하지 마십시오. –

답변

0

이 지정 문에 대한 범위를 작성하십시오. 지시어가 공유 범위를 얻는 것 같습니다. 범위를 선언하면 새 범위 인스턴스를 강제로 가져옵니다.

또한 감시자는 인스턴스가 생성 될 때 실행됩니다. 귀하의 경우, 그것은 scope.domainData 값으로 정의되지 않은 설정입니다.

newValue가 유효한지 확인하거나 $ observe 함수를 사용하십시오. 그냥 빨리 끝

app.directive('customTxt', function($parse) { 
    return { 
    restrict: 'A', 
    templateUrl: 'customtemplate.html', 
    scope : {}, 
    link: function(scope, element, attrs, ctrl) { 
     scope.domainValue = attrs.domaindata; 
     scope.$watch(attrs.domaindata, function (newValue){ 
      console.log('This code will execute when the instance where created. Getting a undefined newValue variable: ', newValue); 
      // verifying if the value is valid to set to the scope. 
      if (newValue != null) { 
       scope.domainValue = newValue; 
      } 
     }); 
    } 
    }; 
}); 

Working plunker

+0

고마워요! 점점 가까워지고 있지만 다음 단계로 나아가려고 노력하고 있습니다.이 접근 방식이 효과가 없을 것 같습니다. 나는 자신을 설명한다 : 모델의 가치는 동적이며, 다른 컨트롤러에 의해 업데이트되고 일반 범위에 저장된다. 그래서 어떻게 든 일반적인 범위에있는 값을 로컬에 바인딩해야한다. 이 솔루션을 사용하면 일반적인 범위에 액세스 할 수 없으며 어떻게 수행 할 수 있습니까? – DreaMTT

+0

흠, 좋아,이 plunker에서 살펴보고 도움이 참조하십시오 : http://plnkr.co/edit/eAFdwi4jztR197wo0QdO?p=in 012 –

+0

고마워 Deividi! 이제 점점 더 가까워지고 있습니다! 내가 정확히 필요한 것은 스코프 간의 양방향 바인딩이 부족한 것입니다. 필자가 원하는 것을 정확히 보여주기 위해 플 런커를 편집했습니다. http://plnkr.co/edit/IBpyZbCV7pOB25oZSYD7?p=preview , 그것은 작동하지만 것 같다 "변경 값"을 클릭하면 전역 범위에서 도메인 중 하나를 업데이트 할 때 로컬 범위를 업데이트하지 않습니다. 권리? – DreaMTT