2016-11-01 2 views
1

나는 HTML <p> 태그를 기반으로 한 아주 간단한 단락 지시어를 만들었습니다.ng-transclude가있는 각도 지시문

<paragraph>This is a very simple paragraph</paragraph> 
<paragraph></paragraph> 

을 그리고 나는 ParagraphViewModel.text에 바인딩 한 입력이 있습니다

angular.module('myApp').directive('paragraph', function() { 
    return { 
    restrict: 'E', 
    transclude: true, 
    controller: function() { 
     var vm = this; 
     vm.text = "Paragraph text from controller" 
    }, 
    controllerAs: 'ParagraphViewModel', 
    template: '<p ng-transclude>{{ParagraphViewModel.text}}</p>' 
    } 
}); 

나는 다음과 같이 내 HTML에서이 지시어를 사용하고 있습니다.

<input type="text" ng-model="ParagraphViewModel.text"> 

문제는 내가 입력을 변경할 때, 두 번째 <paragraph> 변화가 예상하지만 먼저 사람 값을하지 않는 것이다.

실제로 작동하는지 확인하려면 this JSBin을 확인하십시오.

답변

1

여기서 달성하고자하는 것은 지시어에 기본 텍스트를 전달한 다음 바운드 입력으로 변경하는 것입니다.

격리 된 범위를 사용하여이를 달성 할 수 있습니다.

당신의 보기에서 : 여기 당신이 그것을 할 방법입니다 귀하의 에서

<div ng-app="myApp"> 

    <paragraph pgtext="Foo" pgmodel="bar"></paragraph> 
    <paragraph>{{bar}}</paragraph> 
    <input type="text" ng-model="bar"> 

</div> 

:

angular.module('myApp',[]); 

angular.module('myApp').directive('paragraph', function() { 
return { 
    restrict: 'E', 
    transclude: true, 
    scope: { 
     pgmodel: '=', 
     pgtext: '@' 
    }, 
    template: '<p ng-transclude>{{pgmodel || pgtext}}</p>' 
    } 
}); 

DEMO :JSBin

2

특히 example에서 docs을 자세히 살펴보십시오.

당신이 볼 때 완전히 <p ng-transclude>의 모든 콘텐츠는 <paragraph> 태그의 내용으로 대체되기 때문에 약 {{ParagraphViewModel.text}} 지시어의 템플릿에 바인딩 잊어

<paragraph>This is a very simple paragraph</paragraph> 

의 각도 transcludes 콘텐츠.

콘텐츠 교체가 발생하지 않고 Angular가 템플릿의 콘텐츠를 기본값으로 사용하기 때문에 두 번째 사례가 예상대로 작동합니다.

+0

그래서 모든 솔루션이 이거? – sadrzadehsina

+0

무엇에 대한 해결책? :) 그것은 이런 식으로 행동해야합니다. 달성하려는 행동은 무엇입니까? –

+0

@Dennis가 포인트를 얻었다. ng-transclude를 사용하면 각도가 태그를 대체합니다. –