2014-04-06 2 views
1

속성 값 "name"에 따라 이미지를 변경하는 지시문을 작성하고 싶습니다. 이미지가 표시되지만 "이름"속성이 변경되면 업데이트되지 않습니다.DOM을 업데이트하는 AngularJS 지시문

HTML :

<img test name="{{finder.name}}" 

JS :

.directive("test", function() { 
    return { 
     restrict: "A", 
     scope: { 
      name: '@' 
     }, 
     link: function(scope, element, attrs) { 
      scope.$watch("name", function(value) { 
       if (angular.isDefined(value)) 
        var replaceName = value.replace(/[ \/]+/g, "_") 
         .toLowerCase(); 
       var tag = '<img src="/images/banner_' + 
         replaceName + '.jpg" class="img-responsive"/>' 
       element.replaceWith(tag); 
      }) 
     }}} 
    ); 

감사합니다!

답변

0

내가 동적 이미지 소스를 생성하기 위해 .. 내 간단한 이미지 지침에 무슨 짓을

link: function(scope, element, attrs) { 

     // this will replace the value of your image source 
     var setImagrSRC = function() { 
      element.attr('src','some source value here..') 
     } 

     // this will observe if there is changes on your name directive 
     // and will trigger the function setImageSRC above 
     attrs.$observe('name',setImageSRC); 

}}} 
0

이는 replaceWith 메소드를 사용하여 요소를 새 요소로 덮어 쓰기 때문입니다. 당신의 지시는 그것으로 파괴 될 것입니다. 요소를 교체하지 마십시오 그냥 속성을 대체 ..

여기
link: function(scope, element, attrs){ 
    scope.$watch('name', function(value){ 
     ... 
     var imageUrl = value.replace(...); 
     element.attr('src', imageUrl); 
    }); 
}